- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
<!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 −
Advertisements