DEV Community

damanita
damanita

Posted on

How can you execute a function after pressing a button or actually any other HTML element.

Hi there!

Today I am going to show you how you can execute a function after clicking on an HTML element.

You have to query an element from the document. There are few ways you can do it like getElementByClassName or querySelector. I will use getElementById:

For example:

const button = document.getElementById("buton");
Enter fullscreen mode Exit fullscreen mode

Assign a listener to this element (button), which will be triggered a function after the element was clicked:

buton.addEventListener("click", function() {
   alert("Hello there!")
 });

Enter fullscreen mode Exit fullscreen mode

In this case, an alert will be displayed with the text 'Hello there!'

You can also assign a named function:

function clickButton() {
   alert("Hello there!");
 }

 button.addEventListener("click", clickButton);

Enter fullscreen mode Exit fullscreen mode

As I mentioned above, you have several ways to query for an element from a document. Here is a link, with more examples, eg.: how to assign a listener to each element from a list of elements: https://jsfiddle.net/8jo9vhsa/1/

If you have any suggestions, feel free to write a comment.

Thank you!

Top comments (0)