1

Can anyone understand what I'm doing wrong? This code returns the error that "songs is not a function".

<div id="song1" class="song">
    <p>some text</p>
</div>
<div id="song2" class="song">
    <p>some text</p>
</div>
<div id="song3" class="song">
    <p>some text</p>
</div>
const songs = {
    song1: '/media/title-song-lala.mp3',
    song2: '/media/pva.mp3',
    song3: '/media/zjklf.mp3'
};

$('.song').hover(function() {
    let song = songs(this.id);
    createjs.Sound.play(song);
});

Regards, Shape of Mustard

2 Answers2

0

The problem was how you access to your object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

Object properties must be accessed in the following ways songs.song1, or songs['song1'], the latter is useful in cases where the first character of the property is a number in that case you can't do songs.1song, so you will have to do it as songs['1song'] - it is also useful when the property name you want to fetch is a variable.

const songs = {
    song1: '/media/title-song-lala.mp3',
    song2: '/media/pva.mp3',
    song3: '/media/zjklf.mp3'
};

console.log(songs['song1']);

$('.song').hover(function() {
    let id = this.id;
    console.log(songs[id]);
    var audio = new Audio(songs[id]);
    audio.play();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="song1" class="song">
    <p>some text</p>
</div>
<div id="song2" class="song">
    <p>some text</p>
</div>
<div id="song3" class="song">
    <p>some text</p>
</div>
Deepak Kamat
  • 1,880
  • 4
  • 23
  • 38
SKJ
  • 2,184
  • 1
  • 13
  • 25
0
  1. Sorry, my bad about the object-syntax mistake. It should be songs.key instead of songs(key).

  2. The code still doesn't work. I don't get any errors, but there is no audio playing.

const songs = {
    song1: '/media/title-song-lala.mp3',
    song2: '/media/pva.mp3',
    song3: '/media/zjklf.mp3'
};

$('.song').hover(function() {
    let id = this.id
    var audio = new Audio(songs.id);
    audio.play();
});
<div id="song1" class="song">
    <p>some text</p>
</div>
<div id="song2" class="song">
    <p>some text</p>
</div>
<div id="song3" class="song">
    <p>some text</p>
</div>