I have two divs:
<div class="gif_left">
<div class="gif_right">
Initially, the first one has opacity 1, and the second one has opacity 0.
I want onclick function on .gif_left
and change its class on .click
:
.click { opacity: 0; }
And I also want that at the same onclick function change class .gif_right
on:
.click2 { opacity: 1; }
When I click again, everything returns as it was.
Now I have only been able to assign onclick function to .gif_left
and change its class to .click (it also works when you click again by toggleClass):
$(document).ready(function() {
$('.gif_left').click(function () {
$(this).toggleClass('click');
});
});
3
Answers
If I’m understanding your question correctly, I think the easiest way to do this is to use jQuery to find the elements you want and toggle them both in the same handler:
That is, instead of using
$(this)
, use a jQuery selector to find the element. If you do this on a very large complex page, you may need to optimise it, but for a simple example it should work fine.Pro-tip: if you’re using opacity to dynamically turn things on/off, you may want to also add a CSS transition to animate the effect. For a two-second transition, just update your CSS for
.click
and.click2
to addtransition: opacity 2s;
.Can you please try to run the code snippet below. I manipulated their background color to make it more obvious. Feel free to use the CSS attributes that you want.
Here’s an example which toggles the
transparency
as requested, resetting when clicked again.gif_*
so that theonclick
listener is added to both divs.toggleClass
function to toggle thetransparency
on and off, but cycling over all divs to ensure that all matching divs are toggled.off
so that a quick inspection of the HTML can see whichdiv
is turned off.Note:
click2
has been removed from this example for simplicity because the default opacity of an element is already1
.click
has been renamed tooff
for clarity.As a slight aside, the resulting UI behaves a lot like a radiobutton, and for that reason it may make sense to instead prefer a solution which re-usse the radiobutton with a custom style, if the similarity is correct and intended.