How to "reset" the .replaceWith function in jQuery?

649 views Asked by At

How do I "reset" the .replaceWith function so that the html, css and javascript are returned back to their original state?

The idea is to have an icon replace the text when the user clicks on "contact", and when the user clicks on "back" button, the icon returns back to the "contact" text. Right now, the icon switches back to text, but the text isn't responsive when I try to repeat the function a second time.

Here is the HTML:

<div class="contact">Contact</div>
<button class="back">Back</button>

And the Javascript:

var contactswitch = $('<div class="icon"><i class="fa fa-facebook"></i></div>');
var switchback = $('.contact');

  $('.contact').click(function() {
    $(this).replaceWith(contactswitch)
  });

  $('.back').click(function() {
    $(contactswitch).replaceWith(switchback)
  }); 

Thanks!

1

There are 1 answers

0
Talha On

I think you need to re-assign the click handler on the back button click:

  $('.back').click(function() {
    switchback.click(function() { $(this).replaceWith(contactswitch);});
    $(contactswitch).replaceWith(switchback)
  });