9

I want a link like this: When it's clicked, it changes to text, when mouse out of the text, it returns to link.

HTML:

    <a href="#">click me and change to text</a>

JS:

    $("a").on('click',function(){
        var $lnk = $(this);
        var $replace = $('<span>');
        $replace.text($lnk.text());
        // Link to Text
        $lnk.replaceWith($replace);
        // Text to Link
        $replace.one('mouseout',function(){
            $replace.replaceWith($lnk);
        });
        return false;
    });

The code only works first time. Seems that $("a").on("click",function(){}) not working after replaceWith.

fiddle: http://jsfiddle.net/uABC9/4/

I am using jQuery 1.10.1 and tested both FF and Chrome. Please help.

Rich
  • 5,603
  • 9
  • 39
  • 61
andyf
  • 3,262
  • 3
  • 23
  • 37

4 Answers4

17

Replace

$("a").on('click',function(){

by

$(document).on('click','a',function(){

so you can use delegated events. Doing so, your handler will apply for future anchor elements that could be created and this is what you need taking into account that you're removing the anchor from document when executing replaceWith

DEMO

More details about delegated events here (check section "Direct and delegated events")

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
3

The jQuery "on" works, but because it is a link so when you click it will link to other place.

Here is one fiddle : http://jsfiddle.net/joydesigner/4f8Zr/1/

Another reason might be your code use $replace.replaceWith($lnk), becuase $lnk is this. So it means it will still use the same text and link.

Here is the code:

$("a").on('click',function(){
  var $lnk = $(this),
      $replace = $('<span>');

$replace.text($lnk.text());
// Link to Text
$lnk.replaceWith($replace);

// Text to Link
$replace.one('mouseout',function(e){
    $replace.replaceWith('<a href="#">test</a>');
});

e.preventDefault();
return false;

});

joydesigner
  • 813
  • 5
  • 11
2

When the document originally loads its watching your a tag for a click. But when the a tag gets replaced with a new one its not longer watching the new tag.

I would reccomend putting a div around your link and having jQuery watch for all link clicks within the div. As shown in my example.

HTML

<div id="test">
   <a href="#">click me and change to text</a>
</div>

jQuery

$("#test").on('click','a',function(){
   var $lnk = $(this);
   var $replace = $('<span>');
   $replace.text($lnk.text());
   // Link to Text
   $lnk.replaceWith($replace);
   // Text to Link
   $replace.one('mouseout',function(){
      $replace.replaceWith($lnk);
   });
   return false;
});

http://jsfiddle.net/uABC9/8/

Trevor
  • 16,080
  • 9
  • 52
  • 83
0

The marked answer is correct, I just wanted to add on my own that if you need to correct the error not for all links, but for, for example, only one, this line will work (follow-unfollow-button is the link id) $(document).on('click', 'a#follow-unfollow-button', function(e) {

Koder 228
  • 200
  • 1
  • 8