Question

I have a hidden div and a link to toggle the div's visibility. The link contains text/html that needs to also toggle ('hide'/'show'). Here is my function:

jQuery('#toggle_filter_link').click(function() {
    jQuery('#searchfilter_wrap').slideToggle("slow");
    jQuery(this).html(jQuery(this).text() == 'Hide ↑' ? 'Show ↓' : 'Hide ↑');
});

This function works as intended until I add the arrows to the HTML (↑ and ↓), at which point it toggles to "Hide ↑" the first time, and then remains stuck.

Here a jsFiddle.

I assume that I need to escape the HTML Entities somehow, but considering that the first switch works I am a bit confused. It's probably something obvious that I'm missing though. :-)

Thanks for the help!

Was it helpful?

Solution

You're comparing text to html

Change jQuery(this).text() to jQuery(this).html().

Note that you might still have issues due to the way that browsers normalise HTML and you would probably be better off testing some other condition.

jQuery('#toggle_filter_link').click(function() {
    jQuery('#searchfilter_wrap').slideToggle("slow");
    var $this = jQuery(this);
    if ($this.hasClass('show')) {
        $this.removeClass('show');
        $this.html('Hide ↑');
    } else {
        $this.addClass('show');
        $this.html('Show ↓');
    }
});

… or just testing for something that isn't going to be normalised:

jQuery('#toggle_filter_link').click(function() {
    jQuery('#searchfilter_wrap').slideToggle("slow");
    jQuery(this).html(jQuery(this).text().indexOf('Hide') > -1 ? 'Show ↓' : 'Hide ↑');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top