The HTML attribute "onclick" can be used to assign Javascript code (usually in the form of a function) to an element that will be activated when the element is clicked. This can be used to perform many different tasks on a website such as changing its appearance or sending data to the server.
Using the onclick attribute in HTML
<button onclick="alert('hello world')">Click me</button>
The HTML above contains a button with an onclick attribute that - when activated- will display an alert popup with the text "hello world".
Remember to use different quotations within the attribute or HTML will see it as the end of the value.
HTML:
<button onclick="testFunction()">Click me</button>
Javascript:
function testFunction(){
alert("hello world");
}
The above code achieves the same task as before but with the use of a function, the advantage of this is that functions can be reused for other purposes and your code will be a lot more understandable.
If you are new to Javascript, take a look at
HTML:
<button id="mainBtn" onclick="firstFunction()">Click me</button>
Javascript:
function firstFunction(){
document.getElementById("mainBtn").onclick=function(){ secondFunction(); };
alert("onclick attribute changed!");
}
function secondFunction(){
alert("hello world");
}
The onclick attribute of the above button is set to activate firstFunction() when clicked. Using document.getElementById().onclick, this function resets the onclick attribute to active secondFunction. Now the second time the button is clicked it will activate secondFunction() and display an alert popup with the text "hello world"
document.getElementById().onclick expects a function, so we have to make sure to surround our code with "function(){ }" otherwise the onclick attribute will be assigned whatever value secondFunction() returns (calling the function in the code will run it instead of assigning it to the attribute) which is not the desired result.
HTML:
<button id="mainBtn" onclick="firstFunction()">Click me</button>
Javascript:
function firstFunction(){
$("#mainBtn").attr("onclick","secondFunction()");
alert("onclick attribute changed!");
}
function secondFunction(){
alert("hello world");
}
Unlike assigning an onclick attribute using pure Javascript with document.getElementById().onclick, jQuery's attr() function allows you to set the onclick attribute using a string just like you would in the HTML document.