Streaming live at 10am (PST)

Javascript Not working


#1

Hi, I’m wondering if anybody knows why this doesn’t work. I have some custom javascript I wanted to write and for some reason I keep getting typeErrors. Not sure why they’re occurring or what the fix would be.

The code is the following:

$(document).ready(function() {

const alienShips = document.getElementsByClassName('ufo')
const conspiracy = document.querySelector('#conspiracy')

const debunk = event => {
    conspiracy.toggleClass('w-hidden-main')
}

  alienShips.addEventListener('click', debunk);

});

I have tried this in the custom code section of webflow as well as after exporting the files and writing JS after all the script tags near the end of the closing body tag.

I have the following code and I keep getting "Uncaught TypeError: alienShips.addEventListener is not a function " as well as a jQuery deferred exception.

I have added code before into projects after export but this is not working at all and I am unsure if there’s something larger at work here or if I’m just writing something incorrectly. Any help would be appreciated!


#2

"Uncaught TypeError: alienShips.addEventListener is not a function "
is being caused because alienShips is an array, not a single element. You cannot add an event listener to an array, you can only add an event listener to a single item.

alienShips is an array becuase document.getElementsByClassName('ufo') returns all elements that have the class name "ufo’ and puts them into an array. If you want to add an event listener to each element in the alienShips array, you must loop over the array and attach an event listener to each element within it:

const alienShips = document.getElementsByClassName('ufo');

for (i = 0; i < alienShips.length; i++) { 
    alienShips[i].addEventListener("click", debunk);
}

Then don’t forget to define debunk, your click event listener will run this function whenever someone clicks an alienShips element:

function debunk() {
    //Whatever that does here
}