Mobile Number Tracker
Trace Mobile Number Earn Money Online
© TechWelkin.com

Change onclick Event of an Element Using JavaScript

Samyak Lalit | October 5, 2011 (Last update: July 9, 2015)

Samyak Lalit is an Indian author and disability rights activist. He is the principal author and founder of projects like TechWelkin, WeCapable, Viklangta, Kavita Kosh among many others.

Although usually it’s not required but sometimes you may want to change the onClick event of a DOM element using JavaScript. When you click on a Document Object Model (DOM) element, it fires an onclick event. We can capture this event in JavaScript and execute a piece of code. In JavaScript, onclick event expects a function as parameter. This function will be executed when the event occurs. Let’s see how we can change the function to be executed on the fly.

Here is an example link / button code:

<a href="#" id="tButton">click me</a>

Following JavaScript code will capture the onlcik event when a user will click on the button with id “tButton” and call a function called “myFunction”:

document.getElementById("tButton").onclick = function() {myFunction()};

function myFunction(){
alert("myFunction called");
}

The onclick property expects a function and NOT a string –so the following code will not work:

document.getElementById("tButton").onclick = "b()";

I hope this was of help to you. Please let me know if you have any question about this topic. I will try to help! Thank you for using TechWelkin!

© TechWelkin.com

2 responses to “Change onclick Event of an Element Using JavaScript”

  1. Pete says:

    Clicking on “click me” does nothing. Looking at the page’s source code, I don’t see where the functions are even defined. And it seems to be rather incomplete. I tried to create a webpage using the code shown, and it doesn’t work. What’s missing?

    • Lalit Kumar says:

      Hi Pete, thanks for the comment. I have updated the code. If you want to execute two different functions in alternating fashion, you may use a toggle variable. If this variable would be set to 1, function abc will execute. And if the variable would be set to 0, function xyz will execute.

Leave a Reply

Your email address will not be published. Required fields are marked *