Setting and changing the onclick attribute with Javascript

If you need to change or assign a value to the onclick attribute of a DOM element, you have two options; you can use either plain Javascript or the popular jQuery library. In this article, we’ll take a look at both methods and some common mistakes that are easy to make.

Assigning the onclick attribute inline

If you decided to set the onclick attribute inline (directly in the HTML element’s declaration), your first instinct might be to try something like this:

<p id="myElement" onclick="function(){alert('Hello World');}" > Click me! </p>

Unfortunately, that would be incorrect. Why? Because you’re merely declaring a function when the button is clicked, not actually running it. To avoid this, you can put your function in a closure. A closure is a bit of Javascript code that runs as soon as the compiler sees it. This is the correct way of setting the onclick attribute of a specific element:

<p id="myElement" onclick="(function(){alert('Hello World');})()" > Click me! </p>

Note the closure syntax, which looks like this: ()(…), where “…” is the code or function you want executed.

Passing in a function name

If you have a function that already exists in your Javascript somewhere else, you can also set a call to that function inline by passing its name into the onclick attribute, like this:

<p id="myElement" onclick="sayHello()" > Click me! </p>

Make sure your sayHello() function is defined somewhere above the element it’s called from in your HTML file; otherwise, you’ll receive a “[function name] is undefined” exception.

Using Javascript to change the onclick attribute

Changing the onclick attribute with plain Javascript is fairly straightforward. You don’t need to worry about closures, as Javascript handles that automatically if you’re changing the onclick attribute from a script. You can do it like this:

document.getElementById("myElement").onclick = function() {
 alert("Goodbye world!");
};

Using jQuery to change the onclick attribute

The popular library jQuery makes it somewhat simpler to change the onclick attribute. The following code is equivalent to the previous, Javascript-only code.

$("#myElement").click(function() {
 alert("Hello World");
});

Final notes

Be aware that you’ll want to put any DOM-modifying functions inside a function that executes when the DOM is ready to be manipulated. Otherwise you’ll be attempting to modify DOM elements that don’t actually exist yet.