Removing data attribute on mouseleave

I have some navigation links that when hovered over creates a data attribute on the body tag which enables me to add a background color to different links which is exactly what I want however what I’d like is when I hover out of those links the data attribute is removed or a class applied so I can add a default color to the nav links.

here is my html setup:

<nav>
    <a href="#">One</a>
    <a href="#">Two</a>
    <a href="#">Three</a>
</nav>

<p class="One">This is class One.</p>
<p class="Two">This is class Two.</p>
<p class="Three">This is class Three.</p>
<p class="One">This is also class One.</p>
<p class="Two">This is also class Two.</p>
<p class="Three">This is also class Three.</p>

This is the javascript that sets the data attribute to the body:

window.addEventListener("load",function(){

    var links = document.querySelectorAll("nav a");
    for(var i=0; i<links.length; i++){
        links[i].addEventListener("mouseover", function(){
            document.querySelector("h1").innerText = this.innerText;
            document.body.setAttribute("data-nav",this.innerText);
        });
    }
});

Answer

The opposite of mouseover is mouseout. The example below demonstrates how you can use data-nav as a parameter to effect the styling of elements within the body.

I’ve added a second javascript function adding a mouseout event to each of the nav a elements, simplying switching mouseover to mouseout. I have cleared the data-nav property and so the CSS styling ceases to apply.

CSS styling via attributes can be done using element[attribute="value"], in your case it would be body[data-nav="Red"]

It is more appropriate to use classes, but the code below works.

window.addEventListener("load",function(){

    var links = document.querySelectorAll("nav a");
    for(var i=0; i<links.length; i++){
        links[i].addEventListener("mouseover", function(){
            document.querySelector("h1").innerText = this.innerText;
            document.body.setAttribute("data-nav",this.innerText);
        });
        
        links[i].addEventListener("mouseout", function(){
            document.querySelector("h1").innerText = "No color selected";
            document.body.setAttribute("data-nav","");
        });
    }
});
body p {
  color: black;
}

body[data-nav="Red"] p {
  color: red;
}
  
body[data-nav="Blue"] p {
  color: blue;
}
  
body[data-nav="Green"] p {
  color: green;
}
 
<nav>

    <a href="#">Red</a>
    <a href="#">Blue</a>
    <a href="#">Green</a>

</nav>

<body>

    <h1>No color selected</h1>
   
    <p class="One">This is class One.</p>
    <p class="Two">This is class Two.</p>
    <p class="Three">This is class Three.</p>
    <p class="One">This is also class One.</p>
    <p class="Two">This is also class Two.</p>
    <p class="Three">This is also class Three.</p>

</body>

Leave a Reply

Your email address will not be published. Required fields are marked *