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/
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.
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;
});
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