2

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!

2
  • Try adding \ before the ;s Commented Feb 7, 2014 at 11:45
  • Adding \ before the ; did not work unfortunately. Commented Feb 7, 2014 at 12:02

1 Answer 1

3

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 ↑');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Changing to .html() did not work, probably because of the way HTML gets normalized as you mentioned... so I am now testing for indexOf('Hide') which works like a charm.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.