How to make a condition for event 'click' inside/outside for multiple divs - JavaScript?


You can use event listeners for clicks.

Example

Following is the code −

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<body>
   <div class="divDemo">
      First Division
   </div>
   <div class="divDemo">
      Second Division
  </div>
</body>
<script>
   document.addEventListener('click', callEventFuncion)
   function callEventFuncion(event) {
      var div = document.querySelectorAll('.divDemo');
      var titleResult = document.querySelectorAll('.my-title');
      var result = Array.apply(0, div).find((v) => v.contains(event.target));
      if (result) {
         console.log(" Incrementing Division Selection");
      }
      else {
         console.log("Incrementing Element Only OutSide of DIV");
      }
   }
</script>
</html>

To run the above program, save the file name “anyName.html(index.html)”. Righ click on the file and select the option “Open with Live Server” in Visual Studio Code editor.

Output

This will produce the following output on console −

Whenever we click the division then it will increment the division part otherwise it will increment outside of division.

Case 1

When user clicks on div section. Here, I have clicked two times on div section. The snapshot is as follows −

The output in console −

Case 2

Now, I am clicking outside the div section seven times. The snapshot is as follows −

This will produce the following output in console −

Updated on: 09-Nov-2020

780 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements