Home > Net >  How can I use the onmouseover event on a nav using its class?
How can I use the onmouseover event on a nav using its class?

Time:10-19

I am new to javascript and am trying to get a mouseover on a nav to make it change color of the nav bar to green. I coded what I thought would work but nothing is happening. The total length of the entire html page is huge, so I am just adding the code I believe affects the nav mouseover. I'm also using getelementsbyclass[2] because it's the 3rd element with the class.

    <nav class="group" onmouseover="func1()">
       <ol>
          <li><a href="index.html">home</a></li>
          <li><a href="artists.html">artists</a></li>
          <li><a href="schedule.html">schedule</a></li>
          <li><a href="venuetravel.html">venue/travel</a></li>
          <li><a href="register.html">register</a></li>
       </ol>
    </nav>

    <script src="_/js/myscript.js"></script>

    <!--myscript.js-->

    function func1() {
       document.getElementsByClassName("group")[2].style.background-color = "green";
    }

CodePudding user response:

In your code, there are many mistakes. The first mistake is in this line of myscript.js:

document.getElementsByClassName("group")[2].style.background-color = "green";

There is no background-color property in JavaScript DOM. Instead, this is how it will look: backgroundColor. So, now myscript.js should look like this:

    function func1() {
       document.getElementsByClassName("group")[2].style.backgroundColor = "green";
    }

The second issue is in the same line, document.getElementsByClassName("group")[2].style.backgroundColor = "green";. document.getElementsByClassName("group") will return an array containing all the elements that have the class of group. In your HTML code, only one element, the <nav> tag has this class. Since array indexing begins with 0, there is no document.getElementsByClassName("group")[2] element. Only the first element with the index of 0 exists in this array. So change that index. Now, your JavaScript code should look like this:

    function func1() {
       document.getElementsByClassName("group")[0].style.backgroundColor = "green";
    }

CodePudding user response:

First of all the Javascript syntax will be

document.getElementsByClassName("group")[0].style.backgroundColor = "green"

And with the code you provided, I just changed ("group")[3] to ("group")[0] and it just works.

  • Related