Reputation: 3386
I have this markup
<div id="content" >
<h1><a href="#">Sample 1</a></h1>
<img src="" alt="sample 1" />
<h1><a href="#">Sample 2</a></h1>
<img src="" alt="sample 2" />
<h1><a href="#">Sample 3</a></h1>
<img src="" alt="sample 3" />
<h1><a href="#">Sample 4</a></h1>
<img src="" alt="sample 4" />
</div>
I want that all images hide when the page loads, then when I click on every "h1", its image slide down and when I click on it again, it slides up. 1- consider that I do not want all images slide down and up when I click on a "h1", just the related image slides up and down.
help me please
Upvotes: 2
Views: 165
Reputation: 206679
Using too many <h1>
elements is not SEO friendly, so use <h2>
!
$('#content h2').next('img').hide();
$('#content h2').click(function( e ){
e.preventDefault(); // prevent default anchor behavior
var img = $(this).next('img');
var isVisible= img.is(':visible') ? img.slideUp() : ($('img').slideUp()) (img.slideDown());
});
This code allows you to toggle opened images but also to re-close the opened one!
var var_name = statement ? (do this if stetement is true) : (do this if false) ;
Upvotes: 3
Reputation: 8949
Also can be done this way:
$(document).ready(function(){
$('#content img').hide();
$('#content a').click(function(evt){
$(this).parent().next('img').slideToggle();
//alert($(this).parent()[0].outerHTML); // parent is H2 test
evt.preventDefault(); // not follow clicked link
});
});
Upvotes: 0
Reputation: 166071
It should be as simple as something like this:
//On DOM ready...
$(function () {
//Hide all `img` elements...
$("img").hide();
//Bind click event handler to `#content`, responds to clicks on `h1`
$("#content").on("click", "h1", function () {
//Find the immediately following sibling and slide it up/down
$(this).next().slideToggle();
});
});
Note that the above takes advantage of event delegation so only one event handler exists instead of one for every h1
element, which is more efficient.
References:
I recommend that you spend some time reading through the jQuery API and getting to know it. It shouldn't have been difficult to figure out the above just by looking at the methods available to you.
Upvotes: 3
Reputation: 9869
You can try
for hiding all images
$("img").hide();
for showing image next to h1, which clicked
$("h1").click(function(){
$(this).next('img').slideToggle();
});
Upvotes: 1