Problems toggling link text with JQ
Question
I try to use this code for toggling text on the link:
var showText="<span>Open</span> ↓";
var hideText="<span>Close</span> ↑";
$('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!
Solution
Use the toggle
helper function:
var showText="<span>Open</span> ↓";
var hideText="<span>Close</span> ↑";
$('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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow