Why Do I Keep Getting .addeventlistener Is Not A Function?
Solution 1:
Calling getElementsByClassName works differently from getElementById. Multiple elements can have the same class name so what is returned is an array. For example, if you want the first item returned because you know there is only one element with the class then
var upTop = document.getElementsByClassName('playlist-item')[0];
would suffice. Otherwise, you can loop through all items in upTop and add the event listener to all of them. In pure JS:
for (var i=0; i < upTop.length;i++) {
upTop[i].addEventListener('click', function() {
wplayer.setup({autostart: true, floating: {dismissable: true}});
window.scrollTo(0, 0);
});
}
Solution 2:
UpTop is a list of elements rather than the element it self.
If you are trying to apply it to one element you can use
upTop[0].addEventListener
Or if its multiple loop over them and bind them individually
Solution 3:
document.getElementsByClassName
returns an HTMLCollection
and HTMLCollection
doesnot have property addEventListener
For Only First Element
var upTop = document.querySelector('.playlist-item');
Using for
loop
If you want to add event listener on all the elements then use for
loop.
var upTop = document.getElementsByClassName('playlist-item');
for(let i = 0;i<upTop.length;i++){
upTop[i].addEventListener('click', function() {
...
});
}
Using forEach
Or you can convert it into array and use forEach()
var upTop = [...document.getElementsByClassName('playlist-item')];
upTop.forEach(a => a.addEventListener(click,() => ...))
Using jQuery
$('.playlist-item').click(function(){
...
})
Solution 4:
You may be better off refactoring your code to take advantage of event delegation. Essentially the technique is used to delegate event handling to a single parent container - this way we don't have to add an event listener on each and every element that we want to register a click handler on.
Here's an example:
//A parent container for event delegation purposesvar containerEl = document.querySelector('#playlist-items-container');
//Add the event handler to the parent container and analyze the target when an element is clicked on
containerEl.addEventListener('click', e => {
//Check if a //playlist-item was clickedif (e.target.className.indexOf('playlist-item') > -1) {
console.log(`${e.target.textContent} was clicked`);
//Do jwplayer.setup(...);//Do window.scrollTo(...);
}
});
<divid="playlist-items-container"><divclass="playlist-item">Playlist item 1</div><divclass="playlist-item">Playlist item 2</div><divclass="playlist-item">Playlist item 3</div><divclass="playlist-item">Playlist item 4</div></div>
Post a Comment for "Why Do I Keep Getting .addeventlistener Is Not A Function?"