0

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/

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yep, I was thinking about jquery
But how would that CSS work on page load to not have an overlay on the first div and then hovering over another div take that off the first element?
0

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.

Comments

0

You can use jQuery's on. For example:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.