Industry213
Industry213

Reputation: 5

Remove onclick on anchor tag using jquery

What's the best way to remove or disable an onclick event on an anchor tag? Here's the html we have set up:

<a onclick="doSomething('')" href="#"><div id="link-text">Link here</div></a>

Tried something like this but it doesn't appear to work:

$('[id="cswp-like-text').parent().prop('onclick',null).off('click');

Upvotes: 0

Views: 3183

Answers (1)

ismnoiet
ismnoiet

Reputation: 4169

Update:
With the new philosophy of React, mixing HTML with JS code is recommended!.

It is considered a bad practice to embed your js code inside html elements (onclick="function(){}" for example ), instead you are encouraged to define events on a script section or inside an external .js file

Coming back to your question you can take advantage of the addEventListener() and removeEventListener() methods provided by JavaScript and supported by modern web browsers, here is a simple example using pure JavaScript (vanilla) :

<a href="#" id="link">mylink</a>

and here the js part of it :

// a function to be executed whenever an event occur 


var myFunction = function (){
      console.log('element with id link is clicked ');
    };

     var a = document.getElementById('link');
    // add event listener for the click event 
    a.addEventListener('click',myFunction);

    // remove the event listener 
    a.removeEventListener('click',myFunction);

A jquery equivalente solution is to use .unbind('event name') :

var a = $('#link');
$(a).unbind('click');

Upvotes: 1

Related Questions