Reputation: 23574
I have markup like this:
<div>
<a href="#">show</a>
</div>
<div class="msg" style="display: none;">message</div>
<div>
<a href="#">show</a>
</div>
<div class="msg" style="display: none;">message</div>
<div>
<a href="#">show</a>
</div>
<div class="msg" style="display: none;">message</div>
I want to show the 'msg' when the parent link is clicked.
Here's what I have:
$('a').click(function(){
$(this).next('.msg').show();
});
However this doesn't work, doesn't do anything. Any suggestions?
Thank you!
EDIT:
This is the exact markup:
<div class="left">
<a href="/checkout/" class="overlay_box no_thanks">« Back</a>
</div>
<div class="right">
<button type="submit" class="button link" href="'.$item->click_url.'">
<span>'.$this->lang->line('next').'</span></button>
</div>
<div class="clear"></div>
<br/>
<div class="message" style="display: none;">
<img src="/assets/img/icon.png" class="left"/>
<p class="left"><b>Complete?</b> Once you have completed (<a href="/help">Help</a>)</p>
<div class="clear"></div>
The click event is on the button.
Upvotes: 2
Views: 449
Reputation: 10653
First of all, target the parent of the <a>
, like this: $('a').closest('div').next('.msg').show()
.
If it's only to show an element and you don't want to navigate to another page then prevent the natural behaviour of the <a>
tag by adding .preventDefault()
or return false
. They both work. Like this:
$('a').click(function(e){
$(this).closest('div').next('.msg').show();
e.preventDefault();
});
You could have used:
$('a').parent().next()...
But apparently the below is more efficient:
$('a').closest( tag ).next()...
Upvotes: 0
Reputation: 7388
$(this).parent().nextAll('.message:first').show();
Since the link is the only element within a div, it has no siblings, so next() returns an empty set for it. You need to get the parent element and call next() for it.
Upvotes: 5
Reputation: 4536
It won't work because the <a>
element is not the parent of the '.msg'
element - it's actually a child of its sibling.
Upvotes: 0