Accessing array elements in javaScript for an eventListener

Design

I am having trouble getting the div elements to change their background colours onmouseover to the colours set in the array colours. I would like it to accomplish the same thing that I would when you replace the line this.style.background = colours[i] with the one below it

//An array of different colours
var colour = ['blue', 'green', 'yellow', 'purple', 'peach', 
              'pink', 'orange', 'magenta', 'black', 'aliceblue'];

var divContainer = document.getElementById('container');
var divS = divContainer.getElementsByClassName('innerDiv');

for (var i = 0; i < divS.length; i++)
{
    divS[i].addEventListener('mouseover', function() {
        this.style.background = colour[i];
    //this.style.background = "gold";
        
    });
    divS[i].addEventListener('mouseout', function() {
        this.style.background = "white";
    });
}
#container{
    height: 100vh;
}

.innerDiv {
    height: 10%;
    width: 100%;
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Understanding JavaScript</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <div id="container">
            <div class="innerDiv">Hover me to change the colour blue</div>
            <div class="innerDiv">Hover me to change the colour green</div>
            <div class="innerDiv">Hover me to change the colour yellow</div>
            <div class="innerDiv">Hover me to change the colour purple</div>
            <div class="innerDiv">Hover me to change the colour peach</div>
            <div class="innerDiv">Hover me to change the colour pink</div>
            <div class="innerDiv">Hover me to change the colour orange</div>
            <div class="innerDiv">Hover me to change the colour magenta</div>
            <div class="innerDiv">Hover me to change the colour black</div>
            <div class="innerDiv">Hover me to change the colour aliceblue</div>
        </div>

        <!--Link to a script-->
        <script type="text/javascript" src="script.js"></script>
    </body>
</html>

Mister Jojo

your problem is about the i of colour[i] because it is undefined when the event become.

change your code from

for (var i = 0; i < divS.length; i++)

to

for (let i = 0; i < divS.length; i++)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related