tags:

views:

60

answers:

1

I try to use this code for toggling text on the link:

var showText="<span>Open</span> &darr;";
var hideText="<span>Close</span> &uarr;";
$('h1').before('<a href="javascript:;" id="hc_toggle_close">' + showText + '</a>');
$('#hc_toggle_close').click(function () {
    $('#hc_toggle_close:contains("Open")').html(hideText);
    $('#hc_toggle_close:contains("Close")').html(showText);
});

But it does not work! As well as an usual if ... else construction. Could someone please point me what's wrong here. Thanks!

+1  A: 

Use the toggle helper function:

var showText="<span>Open</span> &darr;";
var hideText="<span>Close</span> &uarr;";
$('h1').before('<a href="javascript:;" id="hc_toggle_close">' + showText + '</a>');
$('#hc_toggle_close').toggle(
  function () {
    $('#hc_toggle_close').html(hideText);
  },
  function () {
    $('#hc_toggle_close').html(showText);
  }
);

From the documentation of toggle:

Whenever a matched element is clicked, the first specified function is fired, when clicked again, the second is fired. All subsequent clicks continue to rotate through the two functions.

Ayman Hourieh
Thank you!!! It's the solution!
certainlyakey