Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling href on dynamically loading html

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.

like image 460
WhoobWhoob Avatar asked Dec 21 '16 14:12

WhoobWhoob


3 Answers

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>
like image 127
Ori Drori Avatar answered Nov 09 '22 20:11

Ori Drori


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.

like image 26
Zakaria Acharki Avatar answered Nov 09 '22 20:11

Zakaria Acharki


You need to use event delegation. Change the code to use the .on() event binding method:

  $('body').on('click', 'a', function(){ return false;};);
like image 1
Scott Marcus Avatar answered Nov 09 '22 19:11

Scott Marcus