methods for collapsing a div panel using jquery

When I click outside of the expanded div, I want it to close.

This is the HTML code I have:

<div id="panel">
<div>           
        <h1>Welcome to jquery demo</h1>
                <h3>Welcome to jquery demo</h3>
                <h3>Welcome to jquery demo</h3>
                <h3>Welcome to jquery demo</h3>
                <h3>Welcome to jquery demo</h3>
            </div>
</div>
<div class="tab">
            <ul class="loginleft">
            <button class="sc-button g-opacity-transition sc-button-large loginButton" tabindex="0">Log in</button>

        </ul>
        <ul class="login">
            <li class="left">&nbsp;</li>
            <li>Hello Guest!</li>
            <li class="sep">|</li>
            <li id="toggle">
                <a id="open" class="open" href="#">More Info</a>
                <a id="close" style="display: none;" class="close" href="#">Close Panel</a>         
            </li>
            <li class="right">&nbsp;</li>
        </ul> 
    </div> 

This is the JS code:

$(document).ready(function() {

    // Expand Panel
    $("#open").click(function(){
        $("div#panel").slideDown("slow");

    }); 

    // Collapse Panel
    $("#close").click(function(){
        $("div#panel").slideUp("slow"); 
    });     


    // Switch buttons from "Log In | Register" to "Close Panel" on click
    $("#toggle a").click(function () {
        $("#toggle a").toggle();
    });     

});

How can I also close the expanded div when clicked outside the area?

Answer №1

To prevent overloading the click event, consider adding a handler to the document instead...

=> Check if the event.target matches '.close'

$(document).on('click','.close', function(eventObject){
  $('#panel').slideUp("slow"); // Ideal for multiple buttons scattered throughout your content
});

=> Alternatively, verify if the event.target is located outside your panel

Link to Jsfiddle page

(Avoid attaching excessive handlers to the document to maintain browser responsiveness.)

Answer №2

To achieve this functionality, you can utilize the focusout() method.

 $("div#panel").focusout(function(){
        $(this).slideUp("slow"); 
    }); 

Attach an event listener to the "focusout" JavaScript event.

View demonstration on JSFiddle

Answer №3

Consider handling the event at the document level for better control:

$(document).click(function(e){
    if (event.target.id == "open") {
        $("div#panel").slideDown("slow"); 
    }
    else if (event.target.id == "close") {
        $("div#panel").slideUp("slow"); 
    }
    else {
        $("div#panel").slideUp("slow"); 
    }
});  

To see a working example, check out this fiddle: http://jsfiddle.net/VC9eT/

Answer №4

Here are the tools I utilized:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

  <script>
  $( function() {
    $( "#accordion" ).accordion();
  } );
  </script>

Including in HTML:

<div id="accordion">
  <h3>Section 1</h3>
  <div>
    <p>
    Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
    ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
    amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
    odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
    </p>
  </div>
  <h3>Section 2</h3>
  <div>
    <p>
    Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
    purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
    velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
    suscipit faucibus urna.
    </p>
  </div>
  <h3>Section 3</h3>
  <div>
    <p>
    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
    </p>
    <ul>
      <li>List item one</li>
      <li>List item two</li>
      <li>List item three</li>
    </ul>
  </div>
  <h3>Section 4</h3>
  <div>
    <p>
    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.
    </p>
    <p>
    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.
    </p>
  </div>
</div>

For more information on jQuery, visit this link:

https://jqueryui.com/accordion/

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

Decoding an array in JSON format from PHP

Hey there! Currently, I am working with an associative array in my PHP file, which I convert into a JSON object and pass to my JavaScript file. My goal is to loop through this array and identify the item with a matching key. Here's what I have done so ...

Converting a Selenium By object into a CSS selector: A step-by-step guide

When working with Selenium WebDriver, it's a common practice to find elements using the By class. Currently, I'm using a ByChained selector and I'm curious if there's a way to convert a By object to a CSS selector. For instance: By sel ...

Access the HTML file through the Heroku Bash terminal

After deploying my Flask python application on Heroku, I encountered an issue with one line of my python code where I need to open an HTML file for some javascript to execute. While it works fine locally on my Mac, Heroku seems to have trouble recognizing ...

Error encountered during sequelize synchronization: SQL syntax issue detected near the specified number

Four Sequelize Models were created using sequelize.define();. Each model is similar but with different table names. To avoid manual creation of tables in MySQL cli, the decision was made to use sequelize.sync() in the main index.js file to allow Sequelize ...

Modifying HTML tag attributes with inline server scripts

I am working with a submit button and trying to change the background color of the button itself after it has been clicked using inline server tags. <form id="form1" runat="server"> <input type="submit" id="submit" value="Submit" runat="server"/& ...

Understanding the application of JSON data can be simplified by following these

I am looking to manipulate dates by either adding or subtracting them, but I am unsure of how to extract the dates from the other data present. var fetch = require('node-fetch'); fetch('https://api.nasa.gov/planetary/earth/assets?lon=100.7 ...

Looking for assistance on how to conceal the ego_bar on Facebook

// ==UserScript== // @name Disable friend suggestions on Facebook // @namespace facebook // @description Remove friend suggestions on Facebook // @include *.facebook.com // @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min. ...

Using Threejs to move an object using quaternion rotations

A specific object in my program is utilizing a quaternion for rotation. Whenever a user presses a key, the quaternion is updated to rotate the object along its internal axis. The rotations are working flawlessly. In its default state, before any user input ...

Increasing Gap between Tabs in Primefaces AccordionPanel: A Guide

Is there a way to increase the spacing between the tabs of a Primefaces AccordionPanel component? ...

Is there a way to automatically close the dropdown when a button is clicked?

A Bootstrap 5 dropdown menu is displayed below, consisting of labeled checkboxes and equipped with data-bs-auto-close="outside" attribute to auto-close the menu on outside click. <div class="dropdown"> <button type="button" c ...

Add a new value to the translation token using ng-bind

I'm attempting to loop through an element 5 times using ng-repeat and track by $index. Following that, I aim to utilize the value from $index to supplement a translation token. This appended index value corresponds with the token which retrieves the a ...

Align both vertically and horizontally in the center of the body

I have two images aligned vertically inside a wrapper. How do I center the wrapper within the body? What is the best way to center my wrapper inside the body? <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> ...

How to create a personalized attribute for a form in Yii2

Currently, I am working on an active form and I would like to include a custom attribute. This is a standard form field: <?= $form->field($model, 'password')->textInput() ?> I want it to appear as: <label class="input"> < ...

Insert details into Mysql database

This indicates an issue with Line 15 of my code. I would like to include additional details and have them displayed in a table. see image here Error alert: syntax error, unexpected ';' in N:\ftp\compc\ac12mm\untitled folder& ...

What causes a React Ref callback to be invoked multiple times during the initial loading of a page?

To find more information, please visit this URL within the React DOCS. You can also access a version of this code here. I acknowledge that it is recommended to use the useCallback hook in a Functional React Component to create a ref callback according to ...

The multiple lines text box displays an input box

Having a simple issue here, I've set the value of an input text box, but when the page loads it is displaying in multiple lines, and this seems to be happening only on Chrome browser. Can anyone offer any assistance? This is the HTML code for the ...

AngularJS Error: [$injector:modulerr] - I'm new to this

I am not utilizing ngRoute or any Angular service that requires injection. I am injecting my own module and controller as necessary. However, I am still encountering the following error in the console: Uncaught Error: [$injector:modulerr] http://errors.an ...

Why does a black model appear when loading a GLTF model with materials?

I am currently attempting to load a 3D model in glb format. Below is the code snippet: Expected Outcome: Image Current Outcome: Image var renderer = new THREE.WebGLRenderer(); renderer.setSize(1000, 1000); renderer.setPixelRatio(window.devicePixelRati ...

What is the best way to recover past messages from a channel?

I am working on a bot that is supposed to be able to retrieve all messages from a specific server and channel upon request. I attempted to use the channel.messages.cache.array() method, but it only returned an empty array []. How can I efficiently fetch ...

Utilizing ng-bootstrap within a rebranded module

I'm facing an issue with my nav-bar module that utilizes ng-bootstrap: import {NgModule, NgZone} from '@angular/core'; import { CommonModule } from '@angular/common'; import {NavigationComponent} from "./components/navigation/navi ...