Reputation: 4144
I would like to disable clicking on links in the preview and show an error message instead. I came up with a simple solution:
<div id="preview">
<p>There is a <a href="http://google.com">sample</a> link that should not follow to <a href="http://google.com">google.com</a></p>
<ul></ul>
</div>
<button id="btn">Add a new link</button>
JavaScript code:
$('a').on('click', function () {
alert("links are disabled");
return false;
});
$('#btn').on('click', function () {
$('#preview ul').append('<li><p><a href="http://google.com">another link</a></p></li>');
});
It works perfectly fine for the already existing links but not for the new links added via the button.
How to disable links even after adding a new link?
I would like to keep the logic for disabling links out of the code for adding a new links (as there are multiple places that are adding a new link)
JS fidddle: http://jsfiddle.net/bseQQ/
Upvotes: 2
Views: 80
Reputation: 3353
$('#btn').click(function () {
$('#preview ul').append('<li><p><a href="http://google.com">another link</a></p></li>');
});
Upvotes: 0
Reputation: 337570
To capture events on dynamic elements you need to use a delegated selector:
$('#preview').on('click', 'a', function () {
alert("links are disabled");
return false;
});
This is because events are attached on load, and obviously dynamic elements do not exist at that point. A delegate event is attached to a parent element, but only fired when the filtered selector bubbles the event through the DOM.
Upvotes: 3
Reputation: 145408
You'd better use event delegation:
$('#preview').on('click', 'a', function() {
alert('links are disabled');
return false;
});
Here #preview
is used as a static parent element.
Upvotes: 3
Reputation: 34107
Working demo http://jsfiddle.net/P6Hbg/
API: .on
- http://api.jquery.com/on/
This should fit your cause :)
code
$(document).on('click','a', function () {
alert("links are disabled");
return false;
});
Upvotes: 3