How to remove OnClick events with Javascript

JavaScript is an essential tool for web developers, enabling the creation of interactive and dynamic website components.

One of its key features is the ability to assign and manipulate onclick events, which trigger specific functions when a user clicks on a particular element on a web page.  

However, there might be some situations where you need to remove these events, either temporarily or permanently, to alter the behaviour of your web page.  

In this quick tutorial, we’ll guide you through the steps to remove onclick events in JavaScript, helping you gain more control over your web page’s interactivity. 

There are various ways to remove an onclick event handler using JavaScript, we will look at a couple of working examples, breaking down each snippet and you can even try it out yourself.  

Here is some example HTML code to create a clickable button: 

<button id="myButton" onclick="alert('Hello world!')">Click Me</button> 

The HTML code above will create a button to alert the user with a message ‘Hello World!’.

💡 Go to JSFiddle to see it in action.

On JSFiddle, in the bottom right square, you will see a clickable HTML button.

Click it and you’ll be shown this message:

Now we are going to look at ways to prevent this functionality from working.

The following JavaScript will retrieve the HTML button using the ID ‘mybutton’ and then remove the click functionality. 

var button = document.getElementById("myButton"); 
button.onclick = null; 

By setting button.onclick to null, we remove the onclick event handler from the button. When the event handler is null, clicking the button will not trigger any action.  

Give it a try here. If you try clicking the button now, the above message will not display.  

Here is another JavaScript example, this time we’re using removeAttribute. 

var button = document.getElementById("myButton");  

The code retrieves the button element with the ID ‘myButton’ and then removes the ‘onclick’ attribute from it which results in the button being unclickable.  

Give it a try here  

Build, deploy & manage all your sites/apps at scale. Use our high-spec cloud servers to ensure blazing-fast load times, every time. Get market-leading speed, security & customer support.

  • Easy setup & management across multiple cloud platforms
  • WordPress, WooCommerce, Laravel optimisations & more
  • Free Email, DNS, CDN, SSL, SSH, Backups, Security & Git integration all baked-in
  • Global reach with 60+ global data centres

Find out how our Managed Cloud Hosting is perfect for agencies, online stores, developers, multi-site hosting and high traffic sites.

Add comment

Ben Perry

Profile Picture For Ben Perry

Ben is a Technical Salesperson at 20i. He has a keen interest in cyber security, which he explores in his rare free time when not entertaining his toddler.

Follow us

Let's get social! Awesome content, offers & exclusive competitions.