Question

I need my First Link to direct me to a New Link (along with a button to go back to the old link). The First Link successfully links to the New Link but when I click the button to move back to the First Link, it doesn't work. I heard that JQuery's replaceWith() can be reset to it's original state but I'm not sure how that works. I've also tried .html instead of .replaceWith for the sake of it, but that didn't work either.

HTML:

<div class="page"><a href="#">First Link</a></div>

JQuery:

$('.link').click(function(){
    $('.page').replaceWith('<a href="#">New Link</a><button class="back">Go back to First Link</button>');
});
$('.back').click(function(){
    $('.page').replaceWith('<a href="#">First Link</a>');
});

Here's the Fiddle too: http://jsfiddle.net/HqPbP/

Hope someone can help!

Was it helpful?

Solution

LIVE DEMO

As you're creating your buttons dynamically you're interested in the .on() method:

$('.page').on("click", ".link, .back", function( e ){
    e.preventDefault();
    var HTML = {
        "link" : '<a href="#">New Link</a><button class="back">Go back to First Link</button>',
        "back" : '<a href="#" class="link">First Link</a>'
        }

    $('.page').html(HTML[this.className]);
});

also: restore the class .link to the newly generated anchor:

<a href="#" class="link">First Link</a>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top