element click do something in javascript

The simplest way to perform an action when an element is clicked in Javascript is to add a click event listener to that element. Here's an example:

<button id="my-button">Click me!</button>
42 chars
2 lines
index.tsx
const button = document.querySelector('#my-button');

button.addEventListener('click', function() {
    console.log('You clicked the button!');
    // Do something else here...
});
181 chars
7 lines

In the example above, we first select the button element using document.querySelector(). We then add an event listener for the 'click' event to the button element using addEventListener(). When the button is clicked, the anonymous function we pass to addEventListener() will be executed. In this case, we're simply logging a message to the console. You can replace this with any code you want to execute when the button is clicked.

gistlibby LogSnag