Steps for creating a retractable `<ul>` list on click away

I have successfully implemented a <ul> drop-down list, but I am interested in making the list "retract" or disappear back to its original state when clicking away from it. Is this possible?

Check out this FIDDLE

The code snippet below is what I currently have for the drop-down functionality. Since I'm not proficient in JavaScript, I'm unsure of how to achieve the desired retracting effect.

$(function(){
    $('#select').click(function(){
        $('#sel-option').show();        
    });
    $('#sel-option a').click(function(e){
         $('#select').text($(this).text());
         $('#sel-option').hide(); 
        $(this).addClass('current');
        e.preventDefault();
    })
})

Answer №1

Indeed, all you need to do is handle the body click event and prevent the select click from bubbling up (otherwise, it won't open).

$(function(){
    $('#select').click(function(event){
        $('#sel-option').show();
        event.stopPropagation();
    });
    $('#sel-option a').click(function(e){
         $('#select').text($(this).text());
         $('#sel-option').hide(); 
        $(this).addClass('current');
        e.preventDefault();
    })
    $('body').on('click', function(){
        $('#sel-option').hide(); 
    });
})

UPDATED: Check out this updated and functional fiddle: http://jsfiddle.net/Tpf7E/239/

Answer №2

give this a shot

$(function(){

    $(document).click(function (e)
  {
    var container = $(".language");

    if (!container.is(e.target) // if the click's target is not the container...
        && container.has(e.target).length === 0) // ... nor one of its children
    {
        $('#sel-option').hide();        
             show = 0;
    }
});

    var show=0;

    $('#select').click(function(){
        if(show==0){
         $('#sel-option').show();        
         show = 1;
        } else {
             $('#sel-option').hide();        
             show = 0;
        }    
    });
    $('#sel-option a').click(function(e){
         $('#select').text($(this).text());
         $('#sel-option').hide(); 
        $(this).addClass('current');
        e.preventDefault();
    });
});

check out FIDDLE

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

The synchronization of sessions between Socket.IO and Express is proving to be a challenge as

I am currently facing an issue with connecting the sessions of my express API and socket.IO server. It appears that both are storing their sessions independently. The socket.IO server has the connections session, while the express server has the user qid s ...

The navigation links will remain visible even when the unordered list is set to 0% opacity

I've been working on creating a side navigation menu using HTML, CSS, and Javascript. I successfully implemented the function to toggle open and close the navigation, but upon adding a background image, I noticed that the links still appear even when ...

I need assistance finding and selecting multiple checkboxes on the HTML page. Can someone help me locate them?

[![Click here for image][1]][1] [1]: https://i.sstatic.net/7ahkUEeK.png Can someone please provide guidance on enabling the check for this HTML page? I am having trouble locating the checkbox element. ...

Resolving Issues in HTML and the Dynamic Duo of PHP and MySQL

Hey there, I've been a reader for a while now but this is my first time posting. I'm really into PHP and I've been working on a page lately. Right now, I've got the DB connection set up nicely and my SELECT statement is doing exactly wh ...

unable to decrease the dimensions of the image within the next/image component

Why won't the image size change? I've attempted to adjust the width and height in the component and also tried styling with className, but no luck. The image only seems to resize when using a regular img tag. Here is my code: function Header() ...

The background of an HTML button does not appear in IE8

My buttons are not showing up in IE8. I tried adding background: transparent url('..'), but it didn't help. Here is the code: .wpcf7 input.wpcf7-submit { background: url("/wp-content/themes/ASC/images/<?=ICL_LANGUAGE_CODE;?>_submi ...

Having trouble with PHP form not functioning correctly?

Is there a way to display the var_dump with the 'selected country' information? I am having trouble due to an issue with the $res (array) $id. <?php if(isset ($_POST['submit'])) { $id = $_POST['cata']; $api = new ...

Instructions for connecting a button and an input field

How can I connect a button to an input field? My goal is to make it so that when the button is clicked, the content of the text field is added to an array (displayed below) const userTags = []; function addTags(event) { userTags.push(event.target.__ wha ...

Wordpress Custom Post Type with a Sleek Slider Plugin

I am currently using a static slick slider to display testimonials on my website. Instead of hardcoding the testimonials, I want to fetch them from a WordPress custom post type that I have created. Can someone guide me in the right direction: <section ...

Displaying minute scale from right to left using jQuery technology

I successfully created a minute scale that is functioning well, but now I am encountering an issue with displaying my scale. Instead of being oriented left to right, I would like it to be displayed from right to left. Can anyone suggest what might be wron ...

Set tab navigation widget with a fixed height

I am struggling with setting a fixed height for my tabs widget so that when I add more content, it will display a scrollbar instead of expanding endlessly. I have checked the CSS and JS files but cannot figure it out. It is important for me to contain this ...

I am having trouble getting event handlers to work with a group of buttons in JavaScript

I'm facing a problem where I'm attempting to add event handlers to buttons stored in an array. Upon clicking a button, it should trigger a function, but for some reason, it's not working and I can't seem to identify the issue. Below is ...

Utilizing ng-if in AngularJS for displaying JSON data

After generating Json Data from a PHP API, I attempted to formulate a MYSQL Query and PHP Script to achieve my desired outcome. However, the process has become overly complex. $data1 = [ { "IDa": "6", "IDusr": "1", ...

Struggling to transfer information between POST and GET requests in Node/Express

Just diving into node/express, currently developing a weather application that receives location data from a form submission <form method="POST" action="/"> <input id="input" type="text" name="city" placeholder="Search by city or zip code" /> ...

Set up two unique production servers with different environment variables in NextJs

For my Next.js project, I encountered a challenge while deploying a new version of the app to a development server that relies on environment variables from .env.development. Our typical process includes the following steps: Develop the new fe ...

My website, powered by Wordpress, is currently experiencing an issue with excessive whitespace being added to the bottom of the contact form 7 plugin. I am perplexed as to the cause of this issue and

Recently, I've come across an issue with my contact form 7 plugin, which has been integrated into the front-page.php file using the code below: <div id="contact" class="pad-section"> <div class="container"> <h1>Contact Us</ ...

Media publications do not conform to the current trends

I'm currently utilizing the HTML-to-paper plugin to print my content on a printer. However, I've encountered an issue where it doesn't seem to apply any of the styles I've defined within @media print. The challenges I'm encounteri ...

In PHP, a boolean variable will not display on the webpage when echoed

I am facing an issue with my PHP code where certain variables are not being echoed properly in the generated JavaScript. The code is designed to check if specific values are assigned in the $_GET global array and assign default values if they are not prese ...

Switch ng-model in Angular to something different

I am looking to transform my own tag into a template <div><input .../><strong>text</strong></div> My goal is to have the same values in both inputs. Check out the plunker here If I change the scope from scope: {value:' ...

Swapping out the default JavaScript random number generator for my custom JSON-based solution

I've been working on creating a D3 graph to display my data. After following a tutorial, I arrived at this particular piece of code: // 8. An array of objects of length N. Each object has key -> value pair, the key being "y" and the value is a r ...