Home > Net >  How to override the existing onclick() methods of html anchor tags
How to override the existing onclick() methods of html anchor tags

Time:04-29

In a HTML page there are couple of anchor tags with onclick() methods - of which codes I cannot or must not change. However, I can add a new js file or jQuery to this page. How can I add an event listener for click events of those anchor tags - which must be fired/called before those existing onclick() methods? After that the existing onclick() methods should be called. Something like the following.

<a href='#'  onclick='edit()'>Edit First</a>
<a href='#'  onclick='edit()'>Edit Second</a>
<a href='#'  onclick='edit()'>Edit Third</a>

and

const el = document.getElementsByClassName("edit");
el.addEventListener("click", beforeEdit, false);

function beforeEdit() {
 //this should be called before edit(), after that edit() must be called.
}

CodePudding user response:

Remove the attribute, then call edit yourself in your own handler. Also you'll need to iterate over the elements properly - getElementsByClassName returns a collection, not an element.

for (const anchor of document.querySelectorAll('.edit')) {
  anchor.removeAttribute('onclick');
  anchor.addEventListener('click', () => {
    // insert your function code here, then:
    edit();
  });
}

CodePudding user response:

how can get/retrieve that body of edit() method using js and execute it

In other words, your requirement is that the onclick="edit()" is not always edit().

You could use eval but even the MDN page states:

"Executing JavaScript from a string is an enormous security risk."

An alternative, to ensure your code runs first is to insert your code at the start of the onclick=, eg:

$(".edit").attr("onclick", (i, attr) => "beforeEdit();" attr);

Example snippet:

$(".edit").attr("onclick", (i, attr) => "beforeEdit();" attr);

function beforeEdit() {
  console.log("before edit");
}

function edit() {
  console.log("edit");
}
function edit2() {
  console.log("edit2");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href='#'  onclick='edit()'>Edit First</a>
<a href='#'  onclick='edit2()'>Edit Second</a>
<a href='#'  onclick='edit()'>Edit Third</a>

  • Related