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
Avoid duplicate classes you can explicitly remove classes that should not exist. Here is the updated version of your jQuery code:
You need to define the class that you need to hide when you click
.gif_right
. ThetoggleClass()
function checks for the class in a set of elements. You can read it more about it here.Try: