Reputation: 67
I have a page and I want to show some paragraphs after clicking a link, before that it should be hidden. So i wrote a simple JQuery code, but the problem is when I click the open link all the other hidden divs are also shown. My code is given below please advice how to solve the issue.
HTML
<div>
<a href="#" class="open_div">Read More</a>
<div class="expand_div">
<a href="#" class="close_div"><img src="images/close_button.gif" width="50" height="12" alt="Close" border="0" /></a>
<p>My hidden content goes here..</p>
</div>
</div>
and I want to repeat the above <div>
block 7 times. So when I click the first div's Read more button the remaining 6 hidden divs are also showing!!!
JQuery
<script language="JavaScript">
$(document).ready(function(){
$('a.open_div').click(function(){
$('.expand_div').show();
});
$('a.close_div').click(function(){
$('.expand_div').hide();
});
});
</script>
how to solve this issue..?
any answers would be appreciated!
Thanks
Paul
Upvotes: -1
Views: 86
Reputation: 816442
Well, the selectors will select all elements with that class. If you keep your structure like this, you can do the following:
$(document).ready(function(){
$('a.open_div').click(function(){
$(this).next().show();
});
$('a.close_div').click(function(){
$(this).closest('.expand_div').hide();
});
});
As the div is the next sibling of the open link, next()
will select the div and show it. The close link on the other side is a descendant of the div. closest()
will find the closest ancestor that matches the selector.
Of course there are also other ways to select the elements.
See a working DEMO.
Upvotes: 3
Reputation: 39219
You are getting all "expand_div" elements and showing them. You need to only select the appropriate elements as related to this
element.
<script language="JavaScript">
$(document).ready(function(){
$('a.open_div').click(function(){
$(this).siblings('.expand_div').show();
});
$('a.close_div').click(function(){
$(this).parent().siblings('.expand_div').hide();
});
});
</script>
Upvotes: 0
Reputation: 9242
try this instead of your JQuery code:
<script language="JavaScript">
$(document).ready(function(){
$('a.open_div').click(function(){
$(this).parent().find('.expand_div').show();
});
$('a.close_div').click(function(){
$(this).parent().hide();
});
});
</script>
The problem with your code is that it's selecting ALL divs inside your page. and this is not what you want. to solve this issue, this code is only limiting the scope of the action to the current link container, so the other divs will remain as is without any change.
Upvotes: 4
Reputation: 339816
In your open
event you need to open the "next" element in the DOM:
$('a.open_div').click(function() {
$(this).next().show();
});
In your close
event you need to close the enclosing (parent) element:
$('a.close_div').click(function() {
$(this).parent().hide();
});
see http://jsfiddle.net/raybellis/vZbp3/
Upvotes: 0