skip to Main Content

I have two div (they are in the same place but have different z-index) and two css classes:


.gif_left {
z-index: 20;
position: absolute;
margin-top: 130px;
opacity: 1;
}
.gif_right {
z-index: 19;
position: absolute;
margin-top: 80px;
opacity: 0;
}
.click {
opacity: 0;
visibility: hidden;
}
.click2 {
opacity: 1;
visibility: visible;
}

And Jquvery code for them:

$(document).ready(function() {
$('.gif_left').click (function() {
$('.gif_left').toggleClass('click');
$('.gif_right').toggleClass('click2');
});

$('.gif_right').click (function () {
$('.gif_left').toggleClass('click2');
$('.gif_right').toggleClass('click');
}); 
});

Now when I click on .gif_left everything works correctly and its assigned class .click, and .gif_right is assigned class .click2.
But when I click on .gif_right, both divs become visible on the screen. Each div is assigned .click and .click2 at the same time. When I click again .gif_left gets class .click_2 and .gif_right gets .click again.

What do I need to change or add in the code so classes aren’t duplicated?

2

Answers


  1. Avoid duplicate classes you can explicitly remove classes that should not exist. Here is the updated version of your jQuery code:

    $(document).ready(function() {
        $('.gif_left').click(function() {
            $('.gif_left').addClass('click').removeClass('click2');
            $('.gif_right').addClass('click2').removeClass('click');
        });
    
        $('.gif_right').click(function() {
            $('.gif_left').addClass('click2').removeClass('click');
            $('.gif_right').addClass('click').removeClass('click2');
        });
    });
    
    Login or Signup to reply.
  2. You need to define the class that you need to hide when you click .gif_right. The toggleClass() function checks for the class in a set of elements. You can read it more about it here.

    Try:

    $(document).ready(function() {
        // ...
    
        $('.gif_right').click (function () {
            $('.gif_left').toggleClass('click click2');
            $('.gif_right').toggleClass('click2 click');
        }); 
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search