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.
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")
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With