esthrim esthrim - 1 year ago 64
Javascript Question

How to get or fetch button click event listener using javascript or jquery

Is it possible in JavaScript or jQuery to get or fetch the

event listener of a button element? How?

For example the HTML,

<button id="btn1">Button 1</button>

and the jquery :

$("#btn1").on("click", function() {

and i want to do something like this.

// this is what i'm asking ( capture the click event of the button 1)
var f = $("#btn1").attr("onclick") --> undefined;

$("#btn1").on("click", function() {


Answer Source

You can use the onclick property of your element to fetch the onclick listener (i.e. the code attached to the HTML onclick property of the element, or the function assigned to this property).

var button = document.querySelector("#the-button");
var onclick = button.onclick;
<button id="the-button" onclick="alert('thing');">thing</button>

Listeners attached with addEventListener cannot be fetched by design.

Listeners attached with jQuery may be fetched. You can have a look at this question for more information. However I would strongly advise against doing this. It basically consists in hacking the library – i.e. accessing data you should not access to – and is highly inconsistent from a version to another.

Anyqy, if you want to add additional behavior to the button without overwriting the previous behaviors, you do not need to save it. addEventListener or jQuery's on won't erase any previously attached listeners.

var button = document.querySelector("#the-button");
button.addEventListener("click", function(){
  alert('something else');
<button id="the-button" onclick="alert('thing');">thing</button>