Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
onClick
event in JavaScript is a feature that provides a facility to intact with DOM (Document Object Module) element. Suppose you want to show an alert
after clicking on any image, text, etc., you can achieve this by using the onClick
event of JavaScript.
Let's discuss further on onClick
event
To use onClick
, you include it as an attribute within an HTML tag, specifying the JavaScript code you want to run. For example:
html<button onClick="myFunction()">Click me</button>
The above representation of onClick
event shows, that when the button is clicked, the myFunction()
function will get executed assuming you have already written a function named "myFunction" on html or script file 😊. If you have not written the function "myFunction" then let's write the function.
Generally, We can define JavaScript functions on an HTML page or in an external JavaScript file. If you are creating a function on a JavaScript file then you will have to attach the JavaScript file on the HTML page where you are executing the function "myFunction()".
html<script>
function myFunction() {
alert('Button clicked!');
}
</script>
The above script defines the myFunction()
function, which displays an alert when called.
We can pass any parameters within "(...)" braces of a function, it could be a string, object, array anything. Here I have passed a string as a parameter of the greet function for easy use case.
html<button onClick="greet('Hello, world!')">Greet</button>
In the above code, the greet()
function would receive the string 'Hello, world!' as an argument.
Although you can attach an event in any way. But it is highly recommended you should attach an event using the "event listener" method. This opens a way of attaching and removing events as per requirement which can not be achieved by writing inline code.
Attaching an event with an "event listener" makes code cleaner, readable, and portable. Avoid using inline events as much as possible. Because it's very hard to attach events with complex functionality.
Let's attach an event by addEventListener
:
html<button id="myButton">Click me</button>
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button clicked!');
});
</script>
In the above example, we add an event listener to the button element, which is a more structured way to handle the click event. In the same way you can remove the event by calling removeEventListener()
method.
In conclusion, I can say, onClick
is a widely used event handler attribute in HTML that allows you to execute JavaScript code when a specific HTML element is clicked. It's a fundamental tool for adding interactivity to web pages, but best practices encourage separating JavaScript code from HTML and using modern event-handling methods for more complex applications.