How to create the issue:
Here is my example -: http://jsbin.com/equjig/3/edit
I thought the .on('click', func)
function was good for adding events to current elements in the dom, but also for future elements that get added to the dom?
Here is my current javascript :
$(document).ready(function() {
$(".link").on('click', function(e) {
e.preventDefault();
$("#out").append("clicked<br/>");
});
$("#b1").on('click', function() {
$("#p1").append("<a href='#' class='link'>new trigger</a>");
});
here is the HTML
<button type="button" id="b1">add trigger</button>
<p id="p1">
<a href="#" class="link">trigger 1</a>
<a href="#" class="link">trigger 2</a>
</p>
<div id="out"></div>
Note - im using jQuery 1.7
Thanks!
jQuery click not working at the time page loading, jQuery Onclick Method is tried to an element or selector. As a result, the binding will fail if the element we wish to click isn't present when the page is ready.
To turn it on, go to Start > Settings > Devices > Mouse > Related Settings > Additional Mouse Options. The Mouse Properties window will pop up. At the bottom of the Buttons tab, you'll see the ClickLock options. Put a tick in the checkbox to enable it.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
on() differs from . click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas . click() does not.
You are almost there with on ...
working example : http://jsbin.com/equjig/6/edit
$(document).ready(function() {
$('#p1').on('click','.link', function(e) {
e.preventDefault();
$("#out").append("clicked<br/>");
});
});
This will work - you should select a parent div of the .link
elements (i have used $('#p1')
here, like in your jsbin)
.on()
can also behave like .delegate()
which is used like this:
//#p1 is the context and .link is what will be bound to as long as the .link element is a descendant of #p1
$('#p1').on('click', '.link', function(e) {
e.preventDefault();
$("#out").append("clicked<br/>");
});
Here's documentation for .on()
: http://api.jquery.com/on
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