user3304007
user3304007

Reputation: 470

Jquery hover function doesnt run on dynamically added element

This works successfully,

$('[rel=notif]').on({
    mouseenter: function () {
$(this).find('.solnotifkara').css({"opacity":"0.46"});
  },
    mouseleave: function () {
$(this).find('.solnotifkara').css({"opacity":"0.36"});
    }
});

However, if its dynamically added, its not working. I have a click function that works for dynamically added elements,

$(document.body).on('click', '[rel="like"]' ,function(){

alert("works");

});

How can I make hover function work for dynamically added elements ?

Upvotes: 1

Views: 27

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206078

$(document).on({
  mouseenter: function () {
    $(this).find('.solnotifkara').css({opacity:0.46});
  },
  mouseleave: function () {
    $(this).find('.solnotifkara').css({opacity:0.36});
  }
}, "[rel=notif]");  // <<<<< delegate here your dynamic element

$(document).on({
  mouseenter: function () {
    $(this).find('.solnotifkara').css({opacity:0.2});
  },
  mouseleave: function () {
    $(this).find('.solnotifkara').css({opacity:1});
  }
}, "[rel=notif]");  // <<<<< delegate here your dynamic element


// for test only:
$("button").on("click", function(){
  $("body").append('<p><a rel="notif">This is a <span class="solnotifkara">note</span>.</a></p>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>GENERATE</button>

Upvotes: 6

Related Questions