Conceal the div by clicking outside of it

Is there a way to conceal the hidden div with the "hidden" class? I'd like for it to slide out when the user clicks outside of the hidden div.

HTML

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   </head>
   <body>
      <div class="hidden">Here I am !</div>
      <div class="left">Left panel</div>
      <div class="right">Right panel</div>
      <div class="clear"></div>
      <a href="#" id="slide">Show/hide Slide Panel</a>
   </body>
</html>

CSS

.left,
.hidden {
    float: left;
    height: 350px;
}

.left {
    width: 50%;
    background: #fff;
    z-index: 1;
}

.hidden {
    width: 25%;
    z-index: 2;
    position: absolute;
    left: -1000px;
    background: #f90;
    color: #000;
}

.right {
    width: 50%;
    float: right;
    height: 350px;
    background: #000;
    color: #fff;
}

.clear {
    clear: both;
}

JS

$(document).ready(function () {
    $('#slide').click(function () {
        var hidden = $('.hidden');
        if (hidden.hasClass('visible')) {
            hidden.animate({
                "left": "-1000px"
            }, "slow").removeClass('visible');
        } else {
            hidden.animate({
                "left": "0px"
            }, "slow").addClass('visible');
        }
    });
});

I appreciate any help you can provide!

Answer №1

To utilize this code, you have the flexibility to specify which elements on your page can conceal your panel. In this instance, I have selected classes left, right, and clear:

$(document).ready(function () {
    $('#slide').click(function () {
        hide_el ();
    });
    
    $('.left, .right, .clear').click(()=>{
        var hidden = $('.hidden');
        if (hidden.hasClass('visible')) {
            hidden.animate({
                "left": "-1000px"
            }, "slow").removeClass('visible');
        }
    }); 
});

function hide_el (){
      var hidden = $('.hidden');
        if (hidden.hasClass('visible')) {
            hidden.animate({
                "left": "-1000px"
            }, "slow").removeClass('visible');
        } else {
            hidden.animate({
                "left": "0px"
            }, "slow").addClass('visible');
        }
}
.left,
.hidden {
    float: left;
    height: 350px;
}

.left {
    width: 50%;
    background: #fff;
    z-index: 1;
}

.hidden {
    width: 25%;
    z-index: 2;
    position: absolute;
    left: -1000px;
    background: #f90;
    color: #000;
}

.right {
    width: 50%;
    float: right;
    height: 350px;
    background: #000;
    color: #fff;
}

.clear {
    clear: both;
}
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   </head>
   <body>
      <div class="hidden">Here I am !</div>
      <div class="left">Left panel</div>
      <div class="right">Right panel</div>
      <div class="clear"></div>
      <a href="#" id="slide">Show/hide Slide Panel</a>
   </body>
</html>


If you require a body click function, you can employ the following code:

$(document).ready(function () { 
    
$('#slide').click(function () { 

 hide_el ();      
});

});  
 
function body_click(){
  setTimeout(()=>{
   var hidden = $('.hidden');
    $('body').click( function(event) {
      if( $(event.target).closest(hidden).length === 0 ) {
         if (hidden.hasClass('visible')) {
                hidden.animate({
                    "left": "-1000px"
                }, "slow").removeClass('visible');
        };
      }
    }); 
  }, 1000);   
}

function hide_el (){
 
    $('body').unbind('click');
  var hidden = $('.hidden');
    if (hidden.hasClass('visible')) {
        hidden.animate({
            "left": "-1000px"
        }, "slow").removeClass('visible');
    } else {
        hidden.animate({
            "left": "0px"
        }, "slow").addClass('visible'); 
  body_click();  

    }
}
body {
  height: 300px;
}
.left,
.hidden {
    float: left;
    height: 350px;
}

.left {
    width: 50%;
    background: #fff;
    z-index: 1;
}

.hidden {
    width: 25%;
    z-index: 2;
    position: absolute;
    left: -1000px;
    background: #f90;
    color: #000;
}

.right {
    width: 50%;
    float: right;
    height: 350px;
    background: #000;
    color: #fff;
}

.clear {
    clear: both;
}
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   </head>
   <body> 
      <div class="hidden">Here I am !</div>
      <div class="left">Left panel</div>
      <div class="right">Right panel</div>
      <div class="clear"></div>
      <a href="#" id="slide">Show/hide Slide Panel</a>
   </body>
</html>

Answer №2

This piece of code checks to see if you are clicking inside the designated target element or one of its descendants. If not, a specific code will execute. The animation parts have been left out for you to customize. You can view and experiment with the code in action on this fiddle: https://jsfiddle.net/jhe36dmb/1/

$(document).mouseup(function (e)
 {
    var container = $('.hidden');

    if (!container.is(e.target) // Check if the click is not within the container
        && container.has(e.target).length === 0) // Also check if it's not any descendant of the container
    {

      $('.hidden').css('left', '0'); // Run desired code if conditions met
    }
});

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

Transforming a JavaScript object into a different shape

I need help converting a list of team objects containing team names, reporters, and statuses for each day into date-based objects with all teams and their respective statuses for each date. I attempted the following code snippet but did not achieve the de ...

Generating a fresh document in MongoDB using Mongoose, complete with references and assigned ObjectIDs

I've been attempting to use the mongoose create function in order to generate a new document with references, but I'm encountering an error when trying to provide objectIds for those refs. Despite my efforts to find a solution, I have been unsucc ...

Enhance Bootstrap typeahead to accommodate multiple values

I have a basic typeahead setup for searching city names. However, upon selecting a city, I also need to retrieve its latitude and longitude in order to send that data to the backend. $('.typeahead').typeahead({ minLength : 3, source : ...

Issue with invoking controller action in MVC4 via AJAX

Below is the method in my controller: public JsonResult GetRights(string ROLE_ID) { var result = db.APP_RIGHTS_TO_ROLES.Where(r => r.FK_ROLE_ID.ToString() == ROLE_ID).Select(r => r.APP_RIGHTS).ToList(); return Json(re ...

Exploring the world of Node.js, JSON, SQL, and database tables

Hello everyone, I have been working on a project using Node.js and Express framework. My current goal is to create a client-side page that allows users to input form data into a MySQL database. I have managed to successfully insert and retrieve data from ...

Playing with vue component dependencies

During my attempt to run a unit test, I encountered an error when making an axios call. To handle this error, I successfully mocked the call but faced an issue when trying to utilize an external library dependency (specifically, vue-toasted) to display an ...

Transmitting information through Ajax from a submission form

I'm trying to use Ajax to update a database row by its ID. Here is my form: <form id="update_ajax"> <input type="text" name="name" class="test_hide"> <input type="hidden" name="id" value="<?php echo $row['id']; ...

Extracting unique text values from nested div elements within list items using Selenium with Python

Within the HTML code provided, I am looking to extract the text of three variables (descr_confezione, aic_farmaco, and stato_confezione) for each of the four list items: <ul id="ul_lista_confezioni"> <li style="display: list-item;"> &l ...

HTML Data Service for WCF

Is there a way for users to easily display a list of their publications on their websites? I'm considering pulling data from a SSRS database and using a WCF Data Service. However, the WCF Data Service only outputs ATOM or JSON data. Is this the right ...

Malfunction detected in Json autocomplete function

Currently, I am working on implementing an auto-complete search feature using data from my database. The PHP code below creates an array for this purpose: $leaders= mysql_query("SELECT model_name,model_id FROM models ORDER by model_name D ...

Leveraging CasperJS in a typical JavaScript script

I am currently working on a NodeJS project that involves integrating CasperJS. However, I have encountered an issue where the 'casper' module cannot be located. In an attempt to resolve this, I decided to npm install spooky --save based on some s ...

The SimpleHTTPServer is causing Google Maps Places Autocomplete feature to malfunction

Currently, I am implementing a location search feature along with form auto-fill using the google.maps.places.Autocomplete functionality. While accessing the HTML file directly (file:///location.html), everything is functioning as expected. However, when ...

What is causing the hyperlink to fail to redirect to the specified URL upon being clicked?

I am facing an issue with a contact form where I have included a link to refresh a captcha code upon clicking. Additionally, there is jQuery code that ensures a div remains open by applying CSS styles to it. Both of these functionalities work independently ...

Exploring an array of JSON data with HandlebarsJS and BackboneJS

My goal is to showcase a collection of music artists organized by the first letter of their name. This is how I have set up my Backbone View: function (App, Backbone, utils) { // Define a new module. var AllArtists = App.module(); // Create ...

Encountering a "GET" error while attempting to make a post request to a WCF Web

I have been working on an MVC project where I am attempting to post data to a WCF Service using a web form and AJAX call. However, I am encountering an error when the request reaches the WebService and it simply says "GET". Here is a screenshot of the iss ...

Transfer the imageURI to a different HTML page

My mobile app, created using PhoneGap, allows users to select an image from their album. I want to pass that selected image and display it on another HTML page. Does anyone have any suggestions on how to achieve this? Below is the code snippet: selectImag ...

What is the best way to display content at a specific time using Angular?

Whenever a user searches something and no results are found, I display a message. However, when there is content to show, an error message pops up for about 3-4 seconds before disappearing and showing the search results. This is my HTML: <div> &l ...

What are the steps for sorting objects in an array by their data type attribute?

I am currently working with a JavaScript array of people objects that is dynamically rendered from JS. My goal is to implement a filter on the objects based on the selection made in the dropdown menu and matching it with the department attribute specified ...

Challenges arise when utilizing CSS3 animations in conjunction with transitions triggered by toggling a JavaScript class

Struggling to activate an animation while updating a class using JavaScript for a PhoneGap app. Planning on utilizing -webkit- prefixes for compatibility. However, the animations are currently unresponsive in Chrome during testing, both when applied to th ...

Contrast 2 GET objects retrieved from separate controllers

I have 2 collections of data from different controllers. Data Collection 1 (Controller Name): [{id:1,"name":"jakov"},...] Data Collection 2 (Controller Nickname): [{id:1, "nickname" : "jandric", "nameId" :1, "title" : "master"},...] I send data from C ...