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

Having issues with jQuery not functioning on this specific web page across all browsers. The reason behind this puzzling dilemma remains elusive to me

I am experiencing issues with the functionality of my website. The buttons with + signs are meant to be drop-down toggles, and the mini-tabs below them should work as tabs. Additionally, the sample images at the bottom are not loading properly when clicked ...

Uncovering Secret Information with Beautiful Soup 4

I've hit a roadblock with my current project. I'm attempting to extract player names and projections from this website: The plan involves running a script that loops through various PID values, but that part is not causing any issues. The real c ...

tips on utilizing the JSON information transmitted from the backend

$.ajax({ url: '{{ URL('reports/groupsUsersGet') }}', dataType: "json", data: { group_id : $('#group').val(), }, success: function(data) { <li>"i need to insert variable here"</li> }, error: function (data) ...

Adding miscellaneous PHP scripts

When a user clicks on the sample button, my PHP code gets appended. It works fine, but I want to clean up my process. After some research, I learned that using jQuery AJAX is the way to go. The only problem is, I'm not sure how to implement AJAX. I&ap ...

React-Native Error: Invalid element type detected

While attempting to run my React Native app on my iPhone using Expo, I encountered an error displayed in a red background area. Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

Issues with validating the Google Maps API JavaScript tag

Currently working on updating a website to be fully validated with HTML5 using W3C standards. Having trouble validating the Google Maps API JavaScript tag in the code snippet below: <script src="http://maps.googleapis.com/maps/api/js?libraries=places& ...

When utilizing $resource, Protractor experiences a timeout while trying to synchronize with the page

Currently, I am testing Protractor with a small AngularJS application. Here is the test scenario: describe('Testing Protractor', function() { var draftList; it('should count the number of drafts', function() { browser.get(&ap ...

Tips for incorporating the "build" directory into the Travis-CI build process and deployment of an npm module

Currently, I am working with a Typescript module that has a directory ./src And I also have travis-ci set up for the project. language: node_js node_js: - 5.1.0 install: - npm install - npm install -g mocha - npm install -g gulp - npm install -g tsd - ...

Utilizing Javascript to load a vast amount of data onto the browser, followed by initiating an XML

Looking for a solution to send XML requests containing values and content from files obtained by filling out an HTML form. With 5 large files, some exceeding 70 MB, I have implemented JavaScript functions to load file contents and assemble the XML request. ...

Using the 'client-side rendering' and runtime environment variables in Next.js with the App Router

In the documentation for next.js, it's mentioned that runtime environment variables can be utilized on dynamically rendered pages. The test scenario being discussed involves a Next.js 14 project with an app router. On the page below, the environment ...

Developing a dynamic master-details view on a single page with ASP.NET MVC

This is a question related to design and technology. When using ASP.NET MVC, it is possible to create a simple application with two views: one master view that displays all records in tabular form in read-only mode, and another details view for creating n ...

Is it possible to utilize Ajax submit requests within a (function($){...}(jQuery)); block?

As a PHP developer with some knowledge of JavaScript, I am currently using AJAX to send requests to the server. I recently came across the practice of enclosing all code within an anonymous JavaScript function like: (function($){ //code here }(jQuery)). Fo ...

Including files from different directories using PHP

I'm currently involved in a project for school. The index is functioning properly, however, when I click on 'Lab 1 Q1' located at labs/1/1.html, it does direct me to the page but my <?php include('/main-nav.php') ?> isn' ...

Using Javascript/JQuery to attach a javascript object to a form in order to perform a traditional form

On a page, there is a form that consists mostly of plain HTML. One section of the form creates a quite complex multidimensional object using JavaScript. Usually, if I wanted to include a variable in the POST request, I would add an <input type="hidden" ...

Creating a webpage using jQuery and ajax

I am in the process of developing a game using only jQuery and AJAX for navigation and content loading without ever refreshing the page. One issue I am encountering is the need to create functions for every action. For instance: <p onclick="a_function ...

Merge a pair of observables to create a single combined output

Hey there, I'm currently diving into the world of RxJS and reactive programming. One challenge I'm facing is merging two observables. The first observable contains an array of objects called DefectImages[], while the second observable holds an ar ...

Utilize the Bootstrap column push-pull feature on the mobile version of

https://i.stack.imgur.com/yTBIt.png When viewing the desktop version, div A is displayed at the top of the page. However, I would like to move it to the bottom when viewing on a mobile device (col-xs). I have attempted to solve this issue myself without s ...

positioning two out of three items in a navigation menu to the right and the remaining one to the left

I am looking to design a navigation bar that spans the full width of the screen, with the logo on the left side serving as a link back to the home page. Additionally, I want to include elements for register/login and cart. The background color should cove ...

Do [(ngModel)] bindings strictly adhere to being strings?

Imagine a scenario where you have a radiobutton HTML element within an angular application, <div class="radio"> <label> <input type="radio" name="approvedeny" value="true" [(ngModel)]=_approvedOrDenied> Approve < ...

Using jQuery to detect and respond to changes in an asp:RadioButtonList

Upon page load and when a user selects a radio button, the code below focuses on a textbox. However, I am looking to modify it so that if the last radio option "Mail" is chosen, the focus shifts to the btnSubmit control instead of txtPayerName. $(funct ...