Can anyone understand what I’m doing wrong? This code returns the error that “songs is not a function”.
JavaScript
x
10
10
1
<div id="song1" class="song">
2
<p>some text</p>
3
</div>
4
<div id="song2" class="song">
5
<p>some text</p>
6
</div>
7
<div id="song3" class="song">
8
<p>some text</p>
9
</div>
10
JavaScript
1
12
12
1
const songs = {
2
song1: '/media/title-song-lala.mp3',
3
song2: '/media/pva.mp3',
4
song3: '/media/zjklf.mp3'
5
};
6
7
$('.song').hover(function() {
8
let song = songs(this.id);
9
createjs.Sound.play(song);
10
});
11
12
Regards, Shape of Mustard
Advertisement
Answer
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.
JavaScript
1
14
14
1
const songs = {
2
song1: '/media/title-song-lala.mp3',
3
song2: '/media/pva.mp3',
4
song3: '/media/zjklf.mp3'
5
};
6
7
console.log(songs['song1']);
8
9
$('.song').hover(function() {
10
let id = this.id;
11
console.log(songs[id]);
12
var audio = new Audio(songs[id]);
13
audio.play();
14
});
JavaScript
1
10
10
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div id="song1" class="song">
3
<p>some text</p>
4
</div>
5
<div id="song2" class="song">
6
<p>some text</p>
7
</div>
8
<div id="song3" class="song">
9
<p>some text</p>
10
</div>