Categories
JavaScript Answers

How to Add Hover CSS Attributes Via jQuery and JavaScript?

Spread the love

Sometimes, we want to add hover CSS attributes via jQuery and JavaScript.

In this article, we’ll look at how to add hover CSS attributes via jQuery and JavaScript.

Add Hover CSS Attributes Via jQuery and JavaScript

To add hover CSS attributes via jQuery and JavaScript, we can call the jQuery mouseenter and mouseleave methods on the selected element.

For instance, if we have:

<div id='some-content'>
  hello world
</div>

Then we write:

$("#some-content")
  .mouseenter(function() {
    $(this).css("background", "#F00").css("border-radius", "3px");
  }).mouseleave(function() {
    $(this).css("background", "").css("border-radius", "0px");
  });

We select the div with:

$("#some-content")

Then we call mouseenter with a callback that calls css to set the background and border radius on the div when our mouse enters the div.

Likewise, we call mouseleave with a callback that calls css to set the background and border radius on the div when our mouse leaves the div.

Now when we move our mouse in and out of the div, we see different styles applied to the div.

Conclusion

To add hover CSS attributes via jQuery and JavaScript, we can call the jQuery mouseenter and mouseleave methods on the selected element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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