February 28, 2012
Toggling a div with JQuery and having link text switch
Question by joeschmidt
I have some code where you click on a link and jQuery opens a div. In its normal state the link says “Watch Video”, I’d like to have it work so that when the div becomes visible the link text changes to “Close video”. Clicking on the close video link closes the div.
Here is an example of what I’m trying to do: http://jsfiddle.net/XsvG9/
Here’s the actual code:
JS
$("span.trigger a").click(function() {
the_id = $(this).attr('id');
$("#toggle_container-"+the_id).slideToggle(500, function() {
$("span.trigger a"+the_id).text($(this).is(':visible') ? 'Close video' : 'Watch video');
});
});
HTML
<p class="data">Posted Feb 20 | <a href="/supersecret/jsmith/post/399/">0 comments</a> |<span id="votes_count399" class="votes_count"> 0 </span>
<span id="vote_buttons399" class="vote_buttons">faves<a id="399" title="Favorite This" class="vote_up" href="javascript:;">#</a></span> | <span class="trigger"><a id="399" href="javascript:;">Watch video</a></span>
</p>
<div class="hide" id="toggle_container-399" style="display: none;">
<iframe width="555" height="315" frameborder="0" allowfullscreen="" src="http://www.youtube.com/embed/z1c1OIMbmb0"/></div>
</div>
I have it working where the div toggles open, but the link does not switch text. I’ve been staring at this too long, so I would appreciate it if a fresh pair of eyes could help find the error in my ways.
Thanks for your help.