简体   繁体   中英

Jquery function add/remove class from div on button hover

I have this jquery script that I got some help with in creating in order to add/remove an "active" class to a div when hovering over a button.

Below a CodePen of what I have put together:

CodePen Link : https://codepen.io/dustin-keeslar/pen/dapLWM

It works well, however what I'm trying to change is to have whatever button was last hovered on, to keep the "active" class on the content. So that the content only changes when a different button is hovered over.

jQuery(document).ready(function() {

  jQuery(".toggle-button").hover(function() {
    var target = jQuery(this).data("target");

    if (jQuery(this).hasClass("expand")) {
      jQuery(this).toggleClass("expand");

      jQuery("#" + target).removeClass("active");
    } else {
      jQuery(".toggle-button").removeClass("expand");
      jQuery(".hidden-content").removeClass("active");

      jQuery(this).toggleClass('expand');

      jQuery("#" + target).toggleClass("active");
    }

  });
});

This will find a button that has data-target=content1" for example, and when it is hovered over it will toggle an "active" class to a div with the ID "content1". The problem is that when you are no longer hovering, everything disappears. I need the most recent hovered button to keep the "active" class on the content. But I also need the content to change dynamically when the next button is hovered over.

Then fix it to use mouseenter, and move your remove code to the top to remove your classes before adding them back to the element that's been entered. I don't understand exactly what you're trying to do here, but using mouseenter it should be something like:

jQuery(document).ready(function() {

jQuery(".toggle-button").mouseenter(function() {
  jQuery(".toggle-button").removeClass("expand");
 //      jQuery(".hidden-content").removeClass("active");
  $(".active").removeClass("active");
  var target = jQuery(this).data("target");
  jQuery("#" + target).addClass("active");

  if (jQuery(this).hasClass("expand")) {
    jQuery(this).removeClass("expand");

    jQuery("#" + target).removeClass("active");
  }

});
}); 

All you are missing is a check, to ensure the current item matches the target:

 jQuery(this).attr('id') == target

Codepen here: https://codepen.io/anon/pen/VgKOPy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM