Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - `on` event doesn't work after jQuery.replaceWith

Tags:

jquery

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.

like image 591
andyf Avatar asked Oct 03 '13 01:10

andyf


2 Answers

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")

like image 125
Claudio Redi Avatar answered Nov 13 '22 07:11

Claudio Redi


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;

});

like image 29
joydesigner Avatar answered Nov 13 '22 08:11

joydesigner