Activate event in jQuery when clicking on a blank area, away from any div element

I need help figuring out how to hide a div when empty space on the margins of the page is clicked, as opposed to just any area outside of the div. I've managed to achieve this functionality when certain other divs are clicked, but I'm stuck on implementing it for empty space clicks. Here's a simple jsfiddle you can use to experiment with.

Below is the basic jQuery code I am currently using. Is there a way to modify it so that clicking on empty space will make either "text1" or "text2" disappear?

$("#2").click(function() {
   $('#text1').slideUp(300);
});

$("#1").click(function() {
   $('#text2').slideUp(300);
});

Answer №1

To easily hide specific div items when clicked, you can assign a unique class to those elements and implement the following code snippet:

$(document).click(function (event) {//detect click event on document    
    if (!$(event.target).hasClass('MyClass')) {//check if clicked item does not have the specified class
        $('#text2').slideUp(300);//hide text2     
        $('#text1').slideUp(300);//hide text1      
    }      
});

Check out the demonstration: https://jsfiddle.net/tjrsvbuc/3/

Answer №2

I came across this elegant solution here on Stackoverflow:

$(document).mouseup(function (e)
{
    var container = $("#text1, #text2");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.slideUp(300);
    }
});

Updated Fiddle

Answer №3

If you're interested in adding an event in JavaScript, here's a code snippet to help you achieve that: e.stopPropagation();

$(document).ready(function(){
                $("#1").click(function(e){
                    e.stopPropagation(); 
                    $("#text1").slideDown(300);
                });
            });

$(document).ready(function(e){
                $("#2").click(function(e){
                    e.stopPropagation(); 
                    $("#text2").slideDown(300);
                });
            });

$("#2").click(function() {
                $('#text1').slideUp(300);
            });

$("#1").click(function() {
                $('#text2').slideUp(300);
            });

$("body").click(function() {
    $('#text1').slideUp(300);
    $('#text2').slideUp(300);
  });

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

The replace function fails to recognize Cyrillic characters when combined with the /b flag

Struggling with a persistent issue, I've noticed that my code works perfectly with Latin characters but fails to recognize Cyrillic characters when using jQuery. $('p').each(function() { var $this = $(this); $this.html($this.text().re ...

Tips for Validating Radio Buttons in Angular Reactive Forms and Displaying Error Messages upon Submission

Objective: Ensure that the radio buttons are mandatory. Challenge: The element mat-error and its content are being displayed immediately, even before the form is submitted. It should only show up when the user tries to submit the form. I attempted to use ...

Challenges with CSS in Google Chrome web browser (Input field and Submit button)

Having trouble with the alignment of a textbox and button on Chrome, they're not displaying correctly. Here are examples from different browsers; notice how the textbox in Chrome is misaligned. Internet Explorer/Firefox https://i.stack.imgur.com/mf ...

What is the best way to trigger a modal on Bootstrap using a JavaScript/jQuery function?

I encountered an issue while attempting to call a bootstrap modal using a simple button or link, which may be due to a conflict with my select2 plugin (although I am uncertain). I tried appending the button to the select2 dropdown but it doesn't seem ...

How to create a scrolling fixed div that moves horizontally and repositions to the center when the page is maximized

I've been searching for a solution to my problem and have managed to figure out the first part, but there's still one issue that I could use some help with. While I have some knowledge of html, css, and basic php, I'm completely new to javas ...

Patience is key as we wait for the webpage to finish loading

I've been searching for a solution to this issue for quite some time without any success... On my webpage, I have a square texture as the background which is set to repeat in order to fill the entire page. However, when a user first enters my site, t ...

Unable to locate a contact within the state

Currently, I am diving into the world of React by exploring its documentation and challenging myself to build a small chat application. While I have a good grasp on the basics, I am encountering some issues with states. Within my code, there is an object ...

Uh-oh! Angular 6 has encountered an unexpected error with template parsing

I am currently working on an Angular application where I have integrated the FormsModule from '@angular/forms' in my app.module.ts. However, despite this, I keep encountering the error message No provider for ControlContainer. Error log: Uncaug ...

Insert DOM elements at the start of the parent element

I'm currently using the following JavaScript code to insert AJAX responses into a div with an ID of results: document.getElementById("results").innerHTML=xmlhttp.responseText; The issue I am encountering is that this code adds all new elements after ...

An elegant approach to converting a JavaScript object containing key-value pairs into an array of objects, each with a single key-value pair

Essentially, I have an enum that represents different statuses status = {1: "new", 2: "working" ... } and my goal is to transform it into something like status = [{1: "new"}, {2: "working"} ...] in a way that is cl ...

Exploring the capabilities of useRef in executing a function on a dynamically created element within a React/Remix/Prisma environment

I've been trying to implement multiple useRef and useEffect instructions, but I'm facing difficulties in getting them to work together in this scenario. The code structure involves: Remix/React, fetching data from a database, displaying the data ...

Having Trouble Changing CSS with Rails Link_to CSS ID

While following the ruby on rails guide, I came across a specific way to write link_to's with a css id: <%= link_to "About", about_path, id: "third" %> I also attempted: <%= link_to ("About", :id => "third"), about_path %> Although ...

Trouble with displaying results after submitting a form using jQuery ajax

I'm struggling to use ajax to submit a textarea form on the same page. My goal is to show the processed PHP data at the top of the page, but my lack of understanding in ajax is hindering me from achieving this. Here's the PHP code snippet at the ...

Error: The checkbox was clicked, but an undefined property (includes) cannot be read

Link to live project preview on CodeSandbox Visit the product page with checkbox I have developed a code snippet that allows users to filter products by checking a box labeled "Show Consignment Products Only", displaying only those products with the term ...

unable to retrieve data using ajax

Having some trouble with my ajax code that is supposed to print values: success: function(returndata) { $('#first').html("<div id='first' class='progress-bar progress-bar-primary' role='progressbar' aria-valu ...

Stealthy Google Recaptcha integrated with a dynamic AJAX form

My website includes an ajax form: <form id="my_form"> <input type="text" id="field1" /> <input type="submit" value="submit" /> </form> I also have this JavaScript code: document.getElementById("my_form").onsubmit = fu ...

Implementing Winston logging into a React JS project

I am looking to integrate Winston logging into my React application that was created using create-react-app. First, I installed Winston by running the following command: npm install winston Next, I imported Winston into my app.js file like so: import win ...

Why won't the main bar column in Bootstrap extend to the entire width of the page?

https://i.sstatic.net/oh455jA4.pngI've set up a basic row with two child columns: the sidebar column with className='col-md-2' and the mainbar column with className='col-md-10'. The parent row has a display:flex property to positio ...

What is the best way to include my PHP session variable within my JavaScript code?

i have a dynamic table that the enables to perform CRUD operations on a database. after logging in the user is directed to index.php, here a table is displayed with values stored in the database table "ajaxtable". i have joined "ajaxtable" table and "membe ...

Does the use of 'window.location.replace' in Chrome cause a session to be destroyed in PHP when redirecting to a specified page?

Apologies if the question seems a bit convoluted, but let me explain the scenario. Here is an example of an Ajax function I am working with: $.ajax({ url:"../controllers/xx_register.php", type:"POST", data:send, success: function(resp ...