pirelly
pirelly

Reputation: 465

jQuery on(click) doesn't work but on(hover) does

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

Answers (3)

rokuta
rokuta

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

  • Try turn of libraries for parent element
  • You're not using stopPropagation() in parent element ?

Upvotes: 0

danwellman
danwellman

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

Edit

Also, bind the handler before creating the new <div>

Upvotes: 4

Ruben Verschueren
Ruben Verschueren

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

Related Questions