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

Transform an HTML/CSS document into a PDF file

I recently used html/css to create my resume. Is there a method to transform it into a PDF format? Alternatively, do you have any recommendations for using a different tool to write a CV? Any assistance would be greatly appreciated! ...

My current objective is to extract the information from a specific item within a combobox by implementing the following code

alert($("select[name="+this.name+"] option:selected").text()); However, I am not receiving any output unless I explicitly specify the name of the combobox instead of using this.name. This issue may be related to the way quotes are being handled. ...

Is it possible to pass parameters in the .env file in Node.js?

I am storing my file users.env inside routes/querys/users.env module.exports = { GET_USERS: "SELECT * FROM users", CREATE_USER: "INSERT INTO users ("id", "first_name", "last_name", "active") VALUES (NULL, '%PARAM1%', '%PARAM2%', & ...

Spread out elements equally into columns

I am facing a challenge with arranging items within a single div called .wrap. The goal is to place an unknown number of items (.thing) into four columns, stacked on top of each other. <div class="wrap"> <div class="thing"> thing1 </div ...

Using JavaScript to display content on the screen

As a newcomer to Javascript, I'm looking for a way to display my variable on the webpage without utilizing <span> or innerHTML. var pProductCode = $('[name=pProductCode]').val(); $('input[id*="_IP/PA_N_"]').each(function(i){ ...

Several dropdowns causing issues with jQuery and Bootstrap functionality

Can anyone help me identify where I might be making a mistake? The issue is with my fee calculator that increments fees as the user progresses through the form. In this scenario, there is a checkbox that, when clicked, is supposed to display a div showing ...

"Select2 dropdown search bar vanishing act: The hunt for results comes up empty

Currently, I am dealing with a scenario involving two modals, each containing a select2 search dropdown. An issue has arisen where selecting modal one filters the dropdown data effectively. However, upon selecting modal two, although the data is filtered i ...

Having trouble calling REST API in node.js, whereas it works perfectly fine when called from the browser?

My goal is to invoke the WebServer [mongoose embedded webserver] that is currently running on another machine. Here is the code snippet: var express = require('express'); var http = require('http'); var router = express.Router(); /* ...

What is the best way to change the value of a key in a JSON Object?

I am currently utilizing _underscore library. My goal is to change the value of a specific key. var users = [{ "_id": { "$oid":"3426" }, "name":"peeter" }, { "_id": { "$oid":"5a027" }, "name":"ken" }, { "_id": { "$oid":"5999" }, ...

Sending a large number of values unrestrictedly via ajax

I'm currently working on implementing a filter for the Google Maps API on our website. This filter will allow users to display information related to specific locations that they select by checking corresponding checkboxes. As I am still relatively ne ...

Combine values in CSS without any spacing

Currently, I am attempting to create a LESS mixin that can take a numerical value (degrees for rotation) and generate the appropriate CSS code to rotate an element. However, I am facing difficulties trying to handle both "270deg" and the integer "3" (which ...

Issue TS7053 occurs when trying to access any index of the target of a React.FormEvent<HTMLFormElement>

I've been working on adapting this tutorial to React and TypeScript. Here is the code snippet I have implemented for handling the onSubmit event: const handleSignUp = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); ...

Complicated "as-label" for understanding expressions in Angular

Is it possible to set a complex label in a comprehension expression in Angular? I've searched everywhere for a solution, but I can't seem to find one. The workaround I found involves pre-populating the 'as' label attribute with the des ...

Why isn't the background color displaying for the child text element during animation?

My search boxes are arranged in a grid layout with the use of the display: grid property. When I click on or focus on the <input type="text"> elements in column 1, the text elements within the <span> tag with class names placeholder2, ...

Having trouble sending data to a Django function with Ajax request

I am currently facing an issue with my AJAX calls in Django. While fetching data works seamlessly, adding new data is resulting in an error message. Method Not Allowed (POST): /mymodels/ Method Not Allowed: /mymodels/ [17/Mar/2020 22:27:24] "POST /mymodel ...

Redirecting to a separate component outside the current structure and transferring a callback function

How can I navigate from App.js, the default component, to a new component that is not within the hierarchy while passing a function? I have three components: Question for displaying questions, Upvote for upvoting, and Downvote for downvoting. Here is the ...

Demonstrate HTML and CSS integration through the use of the http.get method

In an attempt to create an iframe-like solution, I am using an http.get call to retrieve a site as an object containing HTML and CSS. The issue arises when using <link> tags because the CSS path is obtained from an external source, causing the HTML t ...

What are the best methods for preserving data when a browser is closed and the system shuts down in PHP projects?

What is the best method to save data in PHP projects before browser closing and system power shutdown? ...

Tips on implementing a script injected through the JS console to update form data in an Angular webpage and ensure that the changes are successfully saved

I am currently working on enhancing an existing electron app integrated with Angular. The main goal is to inject a script once the application is loaded in order to add a hotkey for efficiency. This hotkey should automatically click an edit button, input s ...

Changing the color of text in one div by hovering over a child div will not affect the

When hovering over the child div with class .box-container, the color of another child div with class .carousel-buttons does not change. .carousel-slide { position: relative; width: inherit; .carousel-buttons { position: absolute; z-index: ...