Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable links even after adding a new link?

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/

like image 766
izidor Avatar asked Apr 06 '26 07:04

izidor


2 Answers

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.

like image 134
Rory McCrossan Avatar answered Apr 08 '26 19:04

Rory McCrossan


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;
});
like image 20
Tats_innit Avatar answered Apr 08 '26 21:04

Tats_innit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!