Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove duplicate classes on click in Jquevery?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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');
    });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading