JavaScript Logo

Creating Event Handlers in JavaScript

Over the past 5 years, I had to redesign multiple websites and use some of the previous codebase as to not have to start from scratch. One thing I noticed a lot was previous developers using inline JavaScript click event.

for example,

<button id="reset_btn" class="primary" onClick="resetPage();">RESET</button>

Best practices suggest not to use this type of JavaScript inline event handlers if you can but create an Event Hander that will listen for the button click that will then run the JavaScript function.

Here we just create the normal HTML button.

<button id="reset_btn" class="primary">RESET</button>

Here is our JavaScript. We use the JavaScript window object to load the reset button Event Handler. Now, when the button is clicked, the resetPage function will execute. This is just a simple example that will reload the page.

 
window.onload = function()
{
    document.getElementById('reset_btn').onclick=function(){resetPage();};
}

function resetTP() 
{
    location.reload();
}  

 

Blog, JavaScript,