Why does my banner doesn’t change her background? Please help me.
When I run the file the console tells me:
Uncaught TypeError: flechedroite.addEventListener is not a function
I really don’t understand. I’m a beginner in Javascript so please explain me with kind words how I can fix this error 🙂
var flechedroite = document.getElementsByClassName('fa-arrow-right'); var flechegauche = document.getElementsByClassName('switch-left'); var banner = document.getElementById('banner'); var images = []; var changeBackground = function (bElement, bUrl) { return bElement.style.backgroundImage = "url(" + bUrl + ")"; } //image list images[0] = 'images/image1.jpg'; images[1] = 'images/image2.jpg'; images[2] = 'images/image3.jpg'; flechedroite.addEventListener('click', function() { for (var i = 0; i < images.length; i++) { changeBackground(document.body, images[i]); } })
Advertisement
Answer
- addEventListener should be called in window.onload or in $(document).ready()
- Since getElementsByClassName returns an array, you need to use array index with flechedroite to add an event listener. i.e. flechedroite[0].addEventListener(‘click’, function() {…});
- You are calling changeBackground function in a loop to set the background image, effectively you will see only the last image from the array being set as background.
JS Code
var images = []; var changeBackground = function (bElement, bUrl) { return bElement.style.backgroundImage = "url("+bUrl+")"; } //image list images[0] = 'https://www.gettyimages.ie/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg'; images[1] = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTOGUhZo0Qe81U5qY_Z-seXgsD79LEEet832TVOlLMOEy10ZPsV'; images[2] = 'https://cdn.pixabay.com/photo/2016/06/18/17/42/image-1465348_960_720.jpg'; window.onload = function(){ var flechedroite = document.getElementsByClassName('fa-arrow-right'); var flechegauche = document.getElementsByClassName('switch-left'); var banner = document.getElementById('banner'); var currentImageIndex = 0; flechedroite[0].addEventListener('click', function() { currentImageIndex = (currentImageIndex+1)%images.length; changeBackground(document.body, images[currentImageIndex]); }) }