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
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.
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>