An interesting approach to utilizing toggle functionality in JQuery is by incorporating a feature that automatically closes the div when

Currently, I am utilizing JQuery's toggle function to slide a ul li element. However, my desired functionality is for the div to close if someone clicks outside of it (anywhere on the page) while it is in the toggle Down condition. Below, you'll find the code snippet I am working with:

$('#share-drop').click(function() {
  $('#share-drop ul').toggle(300);
});

$('header .header-top .left-nav .share ul li').click(function(e) {
  e.stopImmediatePropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="share" id="share-drop">
  <img src="images/share-icon.png" alt="">
  <span>Share</span>
  <ul style="">
    <li><a href="javascript:void(0)"><i class="fab fa-facebook-f"> 
          </i>Facebook</a>
    </li>
    <li><a href="javascript:void(0)"><i class="fab fa-twitter"> 
          </i>Twitter</a>
    </li>
    <li><a href="javascript:void(0)"><i class="fab fa-google-plus-g"> 
          </i>Google Plus</a>
    </li>
    <li><a href="javascript:void(0)"><i class="fab fa-linkedin-in"> 
          </i>LinkedIn</a>
    </li>
  </ul>
</div>

Answer №1

Create a click event on the window to hide the ul. Here's how you can do it:

$('#share-drop').click(function(event){
    event.stopPropagation();  // prevents clicks from reaching the window 
    $('#share-drop ul').toggle(300);  
});

// hide the ul when clicking outside the div while it is visible
$(window).on('click', function(){
    if($('#share-drop ul').is(':visible')) {
        $('#share-drop ul').hide(300);
    }
});

$('#share-drop').click(function(event){
    event.stopPropagation();
    $('#share-drop ul').toggle(300);  
});

// hide the ul when clicking outside the div while it is visible
$(window).on('click', function(){
    if($('#share-drop ul').is(':visible')) {
        $('#share-drop ul').hide(300);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="share" id="share-drop">
  <img src="images/share-icon.png" alt="">
  <span>Share</span>
  <ul style="">
    <li><a href="javascript:void(0)"><i class="fab fa-facebook-f"> 
          </i>Facebook</a>
    </li>
    <li><a href="javascript:void(0)"><i class="fab fa-twitter"> 
          </i>Twitter</a>
    </li>
    <li><a href="javascript:void(0)"><i class="fab fa-google-plus-g"> 
          </i>Google Plus</a>
    </li>
    <li><a href="javascript:void(0)"><i class="fab fa-linkedin-in"> 
          </i>LinkedIn</a>
    </li>
  </ul>
</div>

Answer №2

If you want an event to trigger only once, you can set it up to do so within the share-drop event handler. This ensures that the event will not be fired unless the share-drop element is open.

$("#share-drop").click(function(e) {
  e.stopImmediatePropagation();
  var $shareDrop = $("#share-drop ul")
  $shareDrop.toggle(300);
  $("window").one(function() {
    $shareDrop.hide(300);
  });
});
$("header .header-top .left-nav .share ul li").click(function(e) {
  e.stopImmediatePropagation();
});

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

I'm stuck trying to figure out all the parameters for the MapsPage component in Angular 2

Currently, I am utilizing Angular2 with Ionic2 for my mobile app development. Everything was working flawlessly until I decided to incorporate a new module for Google Maps navigation. Specifically, I am using phonegap-launch-navigator for this purpose. The ...

Transforming Form Input into Request Payload for an AJAX Call

I'm facing a challenge in submitting my form data through a POST AJAX request and haven't been able to come across any solutions so far. Due to the dynamic creation of the form based on database content, I can't simply fetch the values usin ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

Having trouble retrieving the Rest Post response using Jquery Ajax post request

When I make a Rest call using the Ajax post method, I encounter the following error or response: {"readyState":0,"status":0,"statusText":"error"} I have enabled cors ($.support.cors = true;) and crossDomain (crossDomain: true (added in headers)). Here ...

Utilizing NextJS to Call the Layout Component Function from the Page Component

I can't seem to find an answer to this question for Next.js after searching online. While there are solutions available for React, I don't think they will work in the Next.js framework. My application is essentially a shop with a navigation menu ...

Refresh content that was previously removed using ajax

Currently, I'm a bit unsure about the best approach to solving this particular challenge. When searching for information on loading and unloading Ajax, most results focus on unloading content before loading new content, rather than reloading previousl ...

The Proper Method of Displaying Data from a JSON File Using AngularJS

I'm having trouble getting the data from a JSON file (click on the "Json File" link to view the structure). I'm not sure what to put after "$Scope.listOfRecipe=". I tried using response.data.recipes, but it's not working and causing errors. ...

What is the manual way to initiate the onclicksubmit event in jqgrid?

Is there a way to manually trigger the onclicksubmit event in jqgrid? If a certain condition is met, I need to programmatically call the submit event. See the code snippet below for reference. afterShowForm: function (formid) { if (condition) { ...

Modifying Array Values in Angular 7

I am currently dealing with a complex array where questions and their corresponding answers are retrieved from a service. Upon receiving the array, I aim to set the 'IsChecked' attribute of the answers to false. The snippet of code I have written ...

Accessing API using Next.js 14

I am facing an issue with the following code which is written in next.js. The error displayed on the console is: GET http://localhost:3000/products/porducts.json 404 (not found) Additionally, I'm encountering this error: Uncaught (in promise) SyntaxE ...

PHP effectively processes data even when the Ajax response is null

I created a form that sends a POST request to a PHP file on the server. The request is processed successfully, but when I attempt to access the response data, it appears as null. Here is my PHP code snippet: <?php header('Access-Control-Allow-Orig ...

Problems Arise Due to HTA File Cache

My JavaScript function fetches the value of a label element first, which serves as an ID for a database entry. These IDs are then sent to an ASP page to retrieve the save location of images from the database. The save location information for each selecte ...

Learn how to call JavaScript code from an HTML file using Ajax

I am encountering an issue with my website. The index.html page contains JavaScript code that triggers an AJAX request to show the content of other.html inside a div in index.html. However, despite the other.html loading correctly, the JavaScript code wit ...

Utilize AngularJS to compile a roster of participants

Just starting out with AngularJS, and although I have some background in JavaScript, AngularJS seems quite challenging to grasp (at least for me). My current issue is as follows... I have a list of players and I want to allow users (such as coaches or an ...

Adjusting date in jQuery UI Datepicker based on current time of day

I am currently developing an online store for a friend, and they have very specific shipping requirements that I need the datepicker functionality to adhere to. Their deliveries only take place on Mondays, Wednesdays, and Fridays. Additionally, at 12pm on ...

Vue.js - Error: Module not found: Cannot locate module 'lottie-vuejs'

I've been attempting to integrate lottie-vuejs into my project. After running the npm install command and following the steps outlined here, I encountered an issue. Unfortunately, I received the following error message: Module not found: Error: Can ...

"Setting the minimum length for multiple auto-complete suggestions in

How can I dynamically set the minLength of an input field based on whether a numeric value is coming from the "#lookup" field? Is there a way to achieve this using JavaScript and jQuery? <script type="text/javascript"> $(document).ready(function() ...

problem with nivo slider causing content to overflow

My webpage is using nivoslider to display images. However, I am facing an issue where the images are overflowing one by one until the page fully loads. I have tried setting the overflow:hidden property in the CSS but it doesn't seem to correct the pro ...

Achieving CSS Buttons That Change to Green When Clicked and STAY Green

I've been tasked with working on a front-end project for a website that involves buttons changing color when clicked and staying that color. Here is the CSS <style> code I have written for these specific buttons: .button { background-color ...

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...