Identify when a click occurs outside specific elements

I've been searching for solutions to address this issue, but so far nothing has worked. Here is the JavaScript code I am using:

var specifiedElement = document.getElementById('a');
document.addEventListener('click', function(event) {
  var isClickInside = specifiedElement.contains(event.target);
  if (!isClickInside) {
    alert('You clicked outside A and B')
  }
});
div {
  background: #aaa;
  height:2em;
  padding: 1em;
  margin-bottom:10px;
  text-align: center;
}
<div id="a">A</div>
<div id="b">B</div>

(View in JS Fiddle: https://jsfiddle.net/1zj9dmq7/)

I am trying to achieve a functionality where the "alert" function only runs when clicking outside of elements a and b, not when clicking on them directly, and without using jQuery. If anyone can assist me with this, I would greatly appreciate it. Thank you.

Answer №1

Give this a shot:

let box1 = document.getElementById('box1');
let box2 = document.getElementById('box2');

document.addEventListener('click', function(event) {
  let isClickInside = box1.contains(event.target) || box2.contains(event.target);
  if (!isClickInside) {
    alert('You clicked outside Box1 and Box2')
  }
});

Check out the live demo here: https://jsfiddle.net/1zj9dmq7/1/

Answer №2

To determine if the id matches any of the two div's ids, simply check the value of event.target.id

var specifiedElement = document.getElementById('a');
document.addEventListener('click', function(event) {
  //var isClickInside = specifiedElement.contains(event.target);
  //console.log(event.target.id);
  if ((event.target.id != 'a') && (event.target.id != 'b')) {
    alert('You clicked outside A and B')
  }
});
div {
  background: #aaa;
  height:2em;
  padding: 1em;
  margin-bottom:10px;
  text-align: center;
}
<div id="a">A</div>
<div id="b">B</div>

Answer №3

Retrieve the element's id using the event object when triggered. Show an alert if it is not 'a' or 'b'

document.addEventListener('click', function(event) {
  if (event.target.id !== 'a' && event.target.id !== 'b') {
    alert('You clicked outside A and B')
  }

});
div {
  background: #aaa;
  height: 2em;
  padding: 1em;
  margin-bottom: 10px;
  text-align: center;
}
<div id="a">A</div>
<div id="b">B</div>

Answer №4

You might want to consider using an event similar to focusLost. I believe jQuery has something along those lines, although I'm not certain of the exact name.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with the overflow issue on Android 4.1 using position: relative and position: absolute

I have a question regarding creating a dynamically filling rounded button. I have successfully created an inner div inside the button with absolute positioning at the bottom. It works perfectly on Chrome webview, but I'm facing issues on Android 4.1. ...

Changing a string into a JavaScript date object

I am encountering an issue where I have a string retrieved from a JSON object and attempting to convert it to a JavaScript date variable. However, every time I try this, it returns an invalid date. Any insights into why this might be happening? jsonObj["d ...

Create reactivity in output by utilizing global functions in Vue

I've recently dived into Vue, along with vue-cli and Single File Components. I'm facing a challenge where I need to have a global function that provides formatted text to components throughout my application. This text should be based on the curr ...

A guide to saving an ArrayBuffer as a file using JavaScript

I am currently developing a file uploader for the Meteor framework. The approach involves breaking down the file on the client side from an ArrayBuffer into small packets of 4096 bits, which are then sent to the server through a Meteor.method. The abridge ...

Can loading HTML and js through ajax be considered secure?

I am currently utilizing the Jquery load function $('#result').load('test.php'); in order to dynamically load a page within another page when clicking on a tab. The page being loaded contains javascript, php, and a form. Upon inspecting ...

How can I extract an object from an array by using a string key in either Observable or lodash?

How can I retrieve a specific object (show) from Shows based on its id being a string in a given sample? I am transforming the result into an RXJS Observable, so using functionalities from RXJS or lodash would be greatly appreciated. //JSON RETURNED with ...

Choose Your Price - Price Grids

I need to incorporate two sets of pricing columns into a website. The first set is for regular car cleaning prices, while the second set is for larger cars with slightly higher prices. My idea is to have two buttons at the top – one for regular cars and ...

Effective methods for synchronizing two dropdown menus with varied displays using React

Having a list of countries with specific key-value pairs, I am interested in creating two Dropdown lists. The first will display the keys, while the second will show the corresponding text values. The main objective is to provide the option to select eith ...

Running asynchronous calls in node.js using express

In my code, there are two functions. The first one: router.post('/getStances', function(req, res, next) { var data = '{"success":"0"}'; data = queries.getStances(req.body.issues[0], req.body.issues[1], req.body.issues[2], req.b ...

What are the different ways to customize the indicator color of React Material UI Tabs using hex

Just got my hands on this amazing Material UI component <Tabs textColor="primary" indicatorColor="primary" > <Tab label="All Issues"/> </Tabs> The documentation states that indicatorColor and textColor can only be set to ' ...

javascript monitoring numerous socket channels for echoes

Currently, I am in the process of developing a chat application. On the server side, I am utilizing: php, laravel 5.4, and pusher. On the client side, I have incorporated vue.js along with laravel-echo. Initially, I successfully created a "public chat roo ...

Easily transfer files from your browser application to your Windows applications such as Outlook or printer queues using a simple drag and

I am attempting to transfer a downloaded file from a web browser to a Windows application (such as Outlook or a printer queue) by dragging and dropping. While I can successfully drop the file onto the desktop or any other file explorer location, I face iss ...

Pass the selected ID from a Vue.js select component to an Axios post request and then render another select

Forgive me if this is a silly question, as I am new to Vue.js and JavaScript. I'm having trouble getting the id from one select element and using it in another API to display models in the next select element. The listings are working fine when I hard ...

What is the process of inserting information into a nuxt-link in nuxt.js?

I am currently facing an issue with passing data into nuxt-link. Whenever I click on the link, nuxt-link returns a 404 error and fails to load the file. However, the other two links that use :href and hardcoding seem to be working fine. <template> ...

It can be challenging to manage numerous if-else conditions in JQuery

I am having trouble with my JQuery code that checks multiple conditions. No matter what I enter, it always goes to the else condition. $(function() { $('#installment').on("keydown keyup", check); function check() { var inst = Number($( ...

Is there a way to execute a Node 6 npm package within a Node 5.6.0 environment?

I am currently utilizing a tool called easy-sauce to conduct cross-browser JavaScript tests. Essentially, my package.json file references this tool for the test command: { "scripts": { "test": "easy-sauce" } } Everything runs smoothly when I exec ...

Pictures change positions in online email interfaces like gmail

Hey there! I'm encountering an issue with the image on my website. The image is contained within a container and seems to extend a bit to the right. Everything looks perfect in all email clients except for web-based ones like Hotmail and Gmail. Here a ...

multiple event listeners combined into a single function

I'm looking to streamline my button handling in JavaScript by creating just one function that can handle all the buttons on my page. Each button will trigger a different action, so I need a way to differentiate between them. I thought of using one eve ...

My navigation bar is giving me a bit of trouble, as there are two separate issues that seem to be interconnected

Looking for some help with my navigation bar layout. You can also check out the code on fiddle http://jsfiddle.net/SgtRx/ (should have done this earlier, sorry). I'm a beginner when it comes to coding, so please bear with me if I make any mistakes. ...

Verify if the form has been refreshed in React JS

In my React application, I have a form inside a modal pop-up. When the user closes the pop-up, I want to check for any changes made in the form fields. If there are changes, I will display a confirmation modal; if not, I will simply close the pop-up. <F ...