Trigger alert when clicking outside of a specific div element

I am trying to implement a feature where an alert pops up if the mouse is clicked outside of the ".square" div element. I have searched extensively for similar mouse events on various websites, but haven't found anything relevant yet. Any help would be greatly appreciated. Thank you.

function myFunction() {
  alert('hi')
}
.square{
width: 100px;
height: 100px;
background-color: red;
}
<div class="square" onclick="myFunction()" ></div>

Answer №1

Easy fix: Just attach a listener to the window triggering an alert, and another listener on the div that prevents the click event from bubbling up, ensuring it doesn't reach the window.

Note: Using stopPropagation can be a bit intrusive, but for experimental purposes, it should suffice.

window.onclick = () => alert('hi')
.square{
  width: 100px;
  height: 100px;
  color: red;
  background-color: teal;
}
<div onclick="event.stopPropagation()" class="square">TEST</div>

Here's a better solution explaining a more appropriate method for achieving this goal.

Now, adapting that solution to your scenario in a more correct manner, where we analyze the click event to decide whether to trigger the alert:

const outsideClickListener = element => ({ target }) => {
  if (!element.contains(target)) {
    alert("hi");
  }
};

const squareEl = document.getElementById("square");
document.addEventListener("click", outsideClickListener(squareEl));
#square{
  width: 100px;
  height: 100px;
  color: red;
  background-color: teal;
}
<div id="square">TEST</div>

Why avoid using stopPropagation? In a small project, using it is generally okay (which is why I recommend it). However, in larger real-world projects, it's discouraged as it could disrupt other functionalities. Consider the example below. Developer A added Test 1 expecting alert('hi 1') to execute whenever the user clicks outside of Test 1. But then developer B introduced Test 2 with stopPropagation that halts all events, causing alert('hi 1') not to run when clicking on Test 2 (outside of

Test 1</code), resulting in a bug.</p>

<p><div>
<div>
<pre class="lang-js"><code>window.onclick = () => alert('hi 2')

const outsideClickListener = element => ({ target }) => {
  if (!element.contains(target)) {
    alert("hi 1");
  }
};

const squareEl = document.getElementsByClassName("square")[0];
document.addEventListener("click", outsideClickListener(squareEl));
.square, .circle {
  width: 100px;
  height: 100px;
  color: red;
  background-color: teal;
}

.square {
  background-color: teal;
}

.circle {
  background-color: wheat;
}
<div class="square">TEST 1</div>
<div onclick="event.stopPropagation()" class="circle">TEST 2</div>

Answer №2

<div class="rectangle">Rectangular</div>
.rectangle{
  width:150px;
  height:200px;
  border:2px solid blue;
}



let rect = document.querySelector('.rectangle');
window.addEventListener('click', function(event){  
    if (rect.contains(event.target)){
       alert('You clicked inside the rectangle!')
    } else{
       alert('You clicked outside the rectangle!')
      }
 });    

Answer №3

Create a click event listener for the body element.

Upon clicking the body, verify if the clicked target is the square or a descendant of the square.

function myFunction() {
  alert('hi');
}
$(document).ready(function(){
$('body').on('click', function(e) {
  if($(e.target).is('.square') || $(e.target).closest('.square').length) {
    myFunction();

  }
});
});
.square{
width: 100px;
height: 100px;
color: red;
background:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="square">
</div>
<body>

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

Within my table, there are multiple columns, the last two of which have the "is-sticky" class. My goal is to add unique styles specifically to the first sticky column

<td> ...</td> ... ... ... <td class="is-sticky">...</td> <-- looking to add a unique style here <td class="is-sticky">...</td> <-- no styles should be applied here Within the provided code snip ...

I am encountering difficulty loading a .gltf file for use with Three.js on my React website

I uploaded my .gltf file of a 3D model to the public folder of my project and then ran the command "npx gltfjsx filename" to convert it into a .js React component. Within that .js file, I included the following line: const { nodes, materials } = useGLTF(&a ...

"Yakov's slender typefaces are appearing incorrectly on the screen

I recently tried to incorporate Yakov thin fonts using CSS @font-face, but I noticed that the fonts appear quite different from the original ones. Any idea why this might be happening? Below is the code snippet I used: @font-face { font-family:' ...

What is the best way to standardize data using normalizr?

After receiving the User object: { "id": "123", "username": "TestUser", "group": { "id": "324", "name": "My Group" } } I am interested in executing: normalize(user); Is it possible to achieve this result? I want to separate th ...

Tips for changing a div's visibility with radio buttons in jQuery

$(':radio').change(function(event) { var id = $(this).data('id'); $('#' + id).addClass('none').siblings().removeClass('none'); }); .none { display: none; } <script src="https://ajax.googleapis.com/ ...

Can you set up an automatic redirect after a payment is made on paypal.me?

Is there a way to automatically redirect users to a "successful payment" landing page after they make a payment on paypal.me? While PayPal offers an "Auto Return" feature, I am uncertain if it is applicable for paypal.me or if there are alternative methods ...

Encountering an error where "null is not an object" while trying to access 'u.default.setString' in React-Native Clipboard

Query As I execute the code sample on snack.expo.io, an error crops up: null is not an object (evaluating 'u.default.setString') Context The following is my code snippet directly sourced from the example available on GitHub: App.js: import R ...

ReactJs - The pagination feature in MaterialTable is malfunctioning, it is not displaying the correct

I am currently utilizing the Material-table plugin. It successfully displays the data, however, I am facing issues with Pagination and Row per Page dropdown functionality. When trying to click on the next button or select a number of rows, nothing happens. ...

Which is more accessible: a disabled textbox or a div with role="textbox"?

Imagine I have a form in which one of the fields (name) is always disabled. When it comes to accessibility, would it be more effective to use an input <label> Name <input role="textbox" aria-readonly="true" value="Joe Shmoe" /> < ...

Video from YouTube keeps playing in the background even after closing Bootstrap modal

I'm having trouble with playing an embedded YouTube video inside a Bootstrap modal. When I close the modal, the video continues to play in the background. Can someone help me with this issue? <!-- Button trigger modal --> <button type=&q ...

The Autocomplete feature in Material UI React includes both a "Select All" and a "Select

How can I add Select All and Select None buttons to an Autocomplete component in Material UI React? The goal is for all the options to be checked when Select All is clicked, and for all options to be unchecked when Select None is clicked. <Autocomple ...

Tips for beginning the process of creating a website's user interface

After initially developing my system without any styling, including bootstrap and CSS, I now find myself needing to add them. While I have reviewed the concepts on W3Schools and have a basic understanding, I am struggling with the sequence of implementat ...

Issues with unresponsive links (HTML5/CSS)

As a beginner, I've encountered an issue where my previously working links are no longer functioning. Can anyone help identify what could be going wrong? Below is the HTML code: <!doctype html> <html> <head> <meta charset="UTF-8 ...

Unusual case of missing lines while reading a file using readline.createInterface()

const readline = require('readline') const fs = require('fs/promises'); (async function() { await fs.writeFile('/tmp/input.txt', [...Array(100000).keys()].join('\n')) await fs.writeFile('/tmp/other.tx ...

Automatically print multiple HTML files with a printer or a Network Printer

I am in search of a way to automatically print multiple HTML files or URLs with just one click from my custom android app. Previously, I utilized the Google Cloud API for this purpose, which involved adding the files to Google Cloud and having them printed ...

Learn how to navigate to another page after successful AJAX request handling

Upon deletion of a file, I am attempting to redirect to the admin_dashboard page using ajax. I have a function called in a button tag, and upon successful response, I want to redirect to the next page. While the value gets deleted successfully, I am facing ...

Is there a way to get an iframe to mimic the behavior of other media elements within a horizontal scrolling container?

Take a look at this code snippet: $(document).ready(function() { $('.scrollable-area').on('wheel', function(e) { var scrollLeft = $(this).scrollLeft(); var width = $(this).get(0).scrollWidth - $(this).width(); var delta ...

Display the name provided in a registration form on the confirmation page as a token of appreciation

I'm attempting to display the user's entered name in a Mailchimp form (where the name value is FNAME) on a custom thank you page (e.g. "Thank you NAME HERE,"). I haven't found a way to do this using Mailchimp's documentation other than ...

Automatically assign a name as an alt attribute

Is there a way in this script to include an alt tag with the value "NikeAir 32" in the given example? <script> function test_options_rendered(){ $('.test_option_value').each(function(){ if( !$(this).parent().hasCla ...

Tips on designing checkboxes with CSS

Can someone help me figure out how to style a checkbox using the code below? <input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" /> I've tried applying this style but it doesn't seem to work. The chec ...