Amit Dangwal
Amit Dangwal

Reputation: 431

how to disable click outside a particular div

Here is the sample code. I want to disable the click outside the search id. Just like we need in pop-up to disable outside click

<body>
You can search <a href="google.com">here</a>
<div id="search">
Search
<input type="text" name=search><button>search</button> 
</div>
</body>

Upvotes: 6

Views: 19337

Answers (3)

Bruno Lucena
Bruno Lucena

Reputation: 484

You can create a div with fixed position that spans the entire screen and place what you want to be able to click inside of it, making all the clicks outside that element actually be on that "empty" div.

.disable-outside-clicks {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 10000;
}

.enabled-clicks {
  width: 200px;
  margin: 0 auto;
}
<div>
  <button>This button will not work</button>
</div>

<div class="disable-outside-clicks">
  <div class="enabled-clicks">
    <button>This button will work</button>
  </div>
</div>

Upvotes: 13

Zenoo
Zenoo

Reputation: 12880

You can use the :not() CSS selector combined with the .preventDefault() JS function :

$('*:not(#search)').click(function(e){
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://google.com">I don't work !</a>
<div id="search"></div>

Upvotes: 3

Joel St&#252;dle
Joel St&#252;dle

Reputation: 367

maybe the css property pointer-events is the thing you are looking for.

add a class to the body element if the pop up is opened. let's say you will add the class .popup to the body element if the pop up is visible. then you can do it like this in css:

body.popup *:not(#search) {
    pointer-events: none;
}

this means, that every element (*) in the body element with the class .popup, except the element #search is not clickable.

Upvotes: 3

Related Questions