I am using this piece of code to disable all links for a preview page:
var disableLink = function(){ return false;};
$('a').bind('click', disableLink);
This disables all links that get loaded staticly. However all tags that get loaded using ajax are still pressable.
How do I make it so that all links so even the dynamically loaded ones get disabled in my preview.
Use CSS - pointer-events: none
. According to MDN:
The element is never the target of mouse events;
You can style the a
tags directly:
a {
pointer-events: none;
}
However, if you don't want to disable all a
tags on a page, you should limit it to anchor elements inside of a container:
#container a {
pointer-events: none;
}
Demo
setTimeout(function() {
$('#container').append('<a href="http://www.facebook.com">Facebook</a>');
$('#child').append('<a href="http://www.yahoo.com">Yahoo</a>');
}, 1000);
#child {
border: 1px solid black;
}
#container a {
pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<a href="http://www.google.com">Google</a>
<div id="child"></div>
</div>
Please don't use bind()
it was deprecated.
As of jQuery 3.0, .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.
You should use event delegation on()
when you deal with new elements added dynamically to the DOM :
$('body').on('click','a', disableLink);
However the css solution posted by @OriDrori looks like the best answer for your case.
Hope this helps.
You need to use event delegation. Change the code to use the .on()
event binding method:
$('body').on('click', 'a', function(){ 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