Show/hide Div By Clicking Image
I want to be able to click on images to show/hide a div (with text). I've got this working for one image, but I have multiple images that need to toggle text. The javascript code
Solution 1:
You forgot to add "."
in $("slidingDiv").slideToggle();
You can also use this
$(document).ready(function() {
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function() {
//$(".slidingDiv").slideToggle();var isvisible = $(this).next('.slidingDiv').is(':visible');
if ( isvisible ) {
$(this).next('.slidingDiv').hide();
} else{
$(this).next('.slidingDiv').show();
}
});
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><ahref="#"class="show_hide"><imgsrc="image.jpg"alt="img"/></a><divclass="slidingDiv"><h2>Title</h2><p>text</p></div>
Solution 2:
Change:
$("slidingDiv").slideToggle();
to
$(this).next(".slidingDiv").slideToggle();
$(".slidingDiv")
, as you noticed, selects all elements with the slidingDiv class. To select the slidingDiv class relative to the element you click on, use this
to refer to the element being clicked on, and then .next(".slidingDiv")
to select the next element as long as it has the class slidingDiv.
Solution 3:
Wrap both in a same div and do the next steps:
- find the parent of the image with .parent()
- find the .slidingDiv of the parent with .find()
- hide/show the .slidingDiv with .slideToggle()
$(document).ready(function() {
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function() {
$(this).parent().find(".slidingDiv").slideToggle();
});
});
.fleft{
float: left;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="fleft"><!-- This is the parent div --><ahref="#"class="show_hide"><imgstyle="width:100px;height:100px"src="http://www.online-image-editor.com//styles/2014/images/example_image.png"></a><divclass="slidingDiv"><h2>Title</h2><p>text</p></div></div><divclass="fleft"><!-- This is the parent div --><ahref="#"class="show_hide"><imgstyle="width:100px;height:100px"src="http://www.online-image-editor.com//styles/2014/images/example_image.png"></a><divclass="slidingDiv"><h2>Title</h2><p>text</p></div></div><divclass="fleft"><!-- This is the parent div --><ahref="#"class="show_hide"><imgstyle="width:100px;height:100px"src="http://www.online-image-editor.com//styles/2014/images/example_image.png"></a><divclass="slidingDiv"><h2>Title</h2><p>text</p></div></div>
Solution 4:
Try this:
$('.show_hide').click(function(e) {
$(e.target).parent().next('.slidingDiv').slideToggle();
});
e.target
will give you the source DOM element for click event
.
Post a Comment for "Show/hide Div By Clicking Image"