I am working on some functionality to show a div containing some text when a user clicks on a link.
The link initially displays the text ‘show +’ and then when the div is revealed this text changes to ‘hide -‘. Code is below:
JQUERY
<script>
$(document).ready(function() {
$('p.link + div').hide();
$('p.link a').prepend('<span>info +</span> ');
$('p.link a').click(function(e) {
var vis = $(this).parent().next().toggle().is(':visible');
$(this).find('span').text(vis ? 'hide -' : 'info +');
e.preventDefault();
});
});
</script>
HTML
<p class="link"><a href="#" class="show-hide"> </a></p>
<div class="info">
<p>Some sample text to show and hide</p>
</div> <!-- info -->
This is all working fine but then I decided rather then an immediate show / hide, it would be nice to gradually reveal the text by adding a speed to the toggle. I therefore amended the following line:
JQUERY
var vis = $(this).parent().next().toggle("slow").is(':visible');
This gives me the transition effect I want but now the link text is not changing. It still initially displays as ‘info +’ but from there on after, regardless of whether or not the div is displayed or not, the link text reads ‘hide -‘.
I assume this is because somehow the code is always seeing the div as being displayed even when it is not but I am unsure of how to fix this.
Any help would be appreciated.
Thanks
Use the callback argument of
toggleto execute your statement after the transition is done, rather than trying to execute it immediately after.JSFiddle