runningantelope123
runningantelope123

Reputation: 138

Removing and adding class on hover

I am making a panel of photos/text. All the panels will have an overlay color on them except the first one which has an active class on page load which removes the overlay. As you hover over the second/third etc panels, the overlay active class will remove from first panel and go onto the one that is hovered.

Right now it is only active on page load, I can't seem to get the class off the first div and onto the second div on hover.

if ( $(".overlay:first") ){
     $(".overlay:first").addClass("active");
     }

else {
    if ( $(".overlay:not(:first)").hover ){
           $(".overlay:first").removeClass("active");
          }

       }    

https://jsfiddle.net/egdkuh16/3/

Upvotes: 0

Views: 5157

Answers (3)

Caleb Eby
Caleb Eby

Reputation: 386

You can use jQuery's on. For example:

$(".overlay:first").addClass("active");
$(".overlay").on("hover", function(){
    $(this).addClass("active");
    $(".overlay:first").removeClass("active")
});

Upvotes: 0

Richard Hamilton
Richard Hamilton

Reputation: 26444

There is no need to use JavaScript or jQuery for this. It's best used in CSS with the :hover pseudo-selector. It's also much easier today.

.overlay:first-child {
   background: white;
}

.overlay:first-child:hover {
  background: gold;
}

If you insist on using jQuery, you can try this

$(".overlay:first").on("mouseover", function() {
    $(this).addClass("active");
}).on("mouseout", function() {
    $(this).removeClass("active");
});
.active {
  background: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="overlay">First overlay class</div>
<div class="overlay">Second overlay class</div>

This approach is highly frowned upon though

Upvotes: 3

emil.c
emil.c

Reputation: 2018

In jQuery, you could do it like this:

$(document).ready(function() {

  // Make the first active
  $(".overlay:first").addClass("active");

  // On hover remove all active classes from .overlay
  // and add .active only to the one that is hovered
  $(".overlay").hover(function() {
    $(".overlay").removeClass("active");
    $(this).addClass("active");
  });

});

but Richard Hamilton's answer is much better and cleaner.

Upvotes: 0

Related Questions