Created by dan on Friday 19th February, 2010 at 11:51 AM
Tags: HTML, Javascript, jQuery, Web development
Not explained very well in the title, but one thing I've found is that there's little supportive documentation on how to alter the text of a link which triggers a slideToggle() or toggle() in jQuery.
To make the toggle a little easier for the user to understand what's happening, they should be seeing a 'Show' or 'Hide' link depending upon the state of the related toggle. This is where the callback function becomes useful.
As mentioned in the jQuery documentation, the callback function is not called with any arguments, however calling 'this' or '$(this)' inside the callback function will return the object, which has been toggled, meaning we can access this element and determine if it's visible or not.
The below code is a simple slideToggle() with a callback to change the text of the link, which calls the toggle on click. It's a bit embarrassing when you see how simple it is.
$('a#toggle_link').click(function(e) {
var toggleLink = this;
e.preventDefault();
$('div#container').slideToggle('fast', function() {
$(toggleLink).text($(this).is(':visible')?'hide':'show');
});
});
Again, I hope this helps somebody. It's more likely to help me in future. I have altered the code for the blog post, so if it it doesn't work it should only need a bit of poking.