Reputation: 465
After initialize js I create new <div>
element with close class and on("click")
function doesn't work.
$(document).on('click', '.post-close', function () {
alert("hello");
});
but on('hover')
work perfectly.
$(document).on('hover', '.post-close', function () {
alert("hello");
});
but I need to make it work on click.
Upvotes: 1
Views: 2529
Reputation: 41
It's an old post but I've had a exactly same problem (element created dynamically, hover works, but click doesn't) and found solution. I hope this post helps someone.
In my case, I found ui-selectable is used for parent element and that was preventing from click event propagate to the document.
So I added a selector of the button element to ui-selectable's 'cancel' option and problem solved.
If you have a similar probrem, check this
Upvotes: 0
Reputation: 9253
It's because you're not preventing the default behaviour of the browser. Pass e
into your handler and then use e.preventDefault()
$(document).on('click', '.post-close', function (e) {
e.preventDefault();
alert("hello");
});
Also, bind the handler before creating the new <div>
Upvotes: 4
Reputation: 842
why not use something like
$('.post-close').click(function(){
//do something
});
If the element was added dynamically use:
$(document).on('click', '.post-close', function(){
//do something
});
edit:
like danWellman said, you can add the preventDefault IF you want to make sure no other code is executed. otherwise use the code above.
edit2:
changed the .live to .on
Upvotes: 1