views:

91

answers:

1

Hi

I'm trying to change the text in an anchor on toggle. I'm doing this way at the moment but have found that once the anchor markup has replaced the toggle no longer works. Can someone please explain why this is happening and a solution? Many thanks.

    $('a#toggleHeader').toggle(function() {
    $('#header-wrapper').slideUp();
    $(this).replaceWith('< href=\"#\" id="toggleHeader">Show Header</>');

//Note:I've move the anchor because I can only post one anchor as a new user

},function(){
    $('#header-wrapper').slideDown();
    $(this).replaceWith('<a href=\"#\" id="toggleHeader">Hide Header</a>');

});
A: 

Simple change the contents of the anchor, instead of replacing the whole thing:

$('a#toggleHeader').toggle(function() {
    $('#header-wrapper').slideUp();
    $(this).html('Show Header');
}, function () {
    $('#header-wrapper').slideDown();
    $(this).html('Hide Header');
});

The reason why it was no longer working, is because the event handlers were being lost when the anchor was being removed (and replaced). If you wanted your example to work, you would either need to rebind the events each time they were replaced, or bind the events using the live() or delegate() methods.

Matt
That explains it. Your example works perfectly. Thanks for pointing me in the direction of live() and delegate() about to read up on them for future reference.
willmcneilly
When setting text on an element, it is more efficient to use [`.text()`](http://api.jquery.com/text/#text2), rather than `.html()` as jQuery will first check the contents of html for HTML before applying. Likewise with plain DOM, it's more efficient to use `innerText`/`textContent` than `innerHTML` because `innerHTML` will invoke the HTML parser.
Andy E
@Andy E's head thanks for the tip. I've changed to .text()
willmcneilly