javascript - jQuery event doesn't work at new created element -
i take img element class ".follow", hide , replace new created element button class ".followbutton". after "mouseout" event take new created button element, hide , replace new created img element class ".follow". have new element img same atributes initially. "mouseenter" doesn't work. , don't figure out why.
$(".follow") .on("mouseenter", function() { $(this).fadeout(150, function() { var init = this; var btn = document.createelement("button"); var t = document.createtextnode("follow"); btn.appendchild(t); btn.classname = "followbutton"; $(btn).hide(); $(this).replacewith(btn); $(".followbutton").show(150); $(".followbutton").on("mouseout", function() { var imgback = $("<img />", { class: "follow", src: "img/remove.png", }).hide(); $(this).hide(150); $(this).replacewith(imgback); $(".follow").show(150); }); }); });
<!doctype html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script type="text/javascript" src="script.js"></script> <title>follow</title> </head> <body> <img src="img/remove.png" class="follow"> </body> </html>
because lost listener on .follow
when creating new img
tag , replace document. have use event delegation instead.
$(document).on("mouseenter", ".follow", function() { /* ... */ });
$(document).on("mouseenter", ".follow", function() { $(this).fadeout(150, function() { var init = this; var btn = document.createelement("button"); var t = document.createtextnode("follow"); btn.appendchild(t); btn.classname = "followbutton"; $(btn).hide(); $(this).replacewith(btn); $(".followbutton").show(150); $(".followbutton").on("mouseout", function() { var imgback = $("<img />", { class: "follow", src: "img/remove.png", }).hide(); $(this).hide(150); $(this).replacewith(imgback); $(".follow").show(150); }); }); });
<!doctype html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script type="text/javascript" src="script.js"></script> <title>follow</title> </head> <body> <img src="img/remove.png" class="follow"> </body> </html>
Comments
Post a Comment