Skip to content
javascript

How to Disable Clicking Inside a Div with JavaScript or CSS?

Jun 3, 2022Abhishek EH1 Min Read
How to Disable Clicking Inside a Div with JavaScript or CSS?

There will be instances where you would want to disable clicking on a div or a section of the page. In this article, we will see how to achieve this in 2 different ways, one using JavaScript and another using CSS.

Disabling click using CSS

Disabling clicking or pressing a div is very simple using css. You just need to add the following line of CSS to the div or any other HTML element.

1.myDiv {
2 pointer-events: none;
3}

You can see in the below example the behavior when the click is disabled on buttons. You can apply the above style for other HTML elements as well, not just buttons.

Disabling click using JavaScript

You can disable any click events on a div or button using JavaScript as shown below:

1<div id="myDiv">Click Me</div>
2
3<script>
4 const myDiv = document.getElementById("myDiv")
5 myDiv.addEventListener("click", e => {
6 e.preventDefault()
7 })
8</script>

You can use e.preventDefault especially if you want to render something as a link and want nothing to happen while the user clicks on it.

1<a href="#" id="myLink">Click Me</a>
2
3<script>
4 const myLink = document.getElementById("myLink")
5 myLink.addEventListener("click", e => {
6 e.preventDefault()
7 })
8</script>

If you have liked article, stay in touch with me by following me on twitter.

Leave a Comment

© 2023 CodingDeft.Com