Refreshing the Dropdown Menu with Jquery

Looking for a way to create a reusable dropdown menu using css/jquery? Check out this codepen: https://codepen.io/anon/pen/NxXXPg

Is there a method to reset the 'active' status when clicking on a blank space or another html element?

Here's the code snippet:

$(document).ready(function(){


   $('.drpd-ver > .label').on('click', function(){
   // Check if active class is there and remove it if it is
   if($( this ).hasClass( "active" )){
   $(this).removeClass('active');
   }
   else{
   // else just remove all other opened tabs and add the needed one
   $('.drpd-ver > .label').removeClass('active');
   $(this).toggleClass('active');
   }   
   });
  
  // removing active class if clicked anywhere else ??

});
body{
    background-color: lightblue;
}
.drpd-ver{
    position: relative;
    display: inline-block;
    font-size: 16px;
    color: #000;
    margin-left:400px;
}

/* Click to expand button */

.drpd-ver label{
    box-sizing: border-box;
    display: inline-block;
    width: 100%;
    background-color: #FFF;
    padding: 15px 20px;
    cursor: pointer;
    text-align: center;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;

    -webkit-transition: .2s;
    transition: .2s;
}


/* The ul will have display:none by default */

.drpd-ver ul{
    position: absolute;
    right: 0;
    list-style: none;
    text-align: left;
    width: 200px;
    z-index: 1;
    box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.2);
    display: none;
    background-color: #DADADA;
    padding: 0;
}

.drpd-ver ul li{
    padding: 15px;
    background-color: #fff;
    color: #656565;
    font-weight: 600;
    margin-bottom: 1px;
    cursor: pointer;
}

.drpd-ver ul li:hover{
    background-color: royalblue;
    color: #FFF;
}

.drpd-ver ul li a{
    color: inherit;
    text-decoration: none;
}

/* Defining active states*/
.drpd-ver .label.active{
    background-color: royalblue;
    color:white;
}

.drpd-ver .label.active + ul{
    display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="drpd-ver">
    <span class="label">\/</span>
    <ul>
        <li><a href="#">Link One</a></li>
        <li><a href="#">Link Two</a></li>
        <li><a href="#">Link Three</a></li>
        <li><a href="#">Link Four</a></li>
    </ul>
</div>

Answer №1

Experience the power of Event Propagation

$('html').click(function() {
$('.drpd-ver > .label').removeClass('active');
});

Implement this

 event.stopPropagation();

$(document).ready(function(){
$('html').click(function() {
$('.drpd-ver > .label').removeClass('active');
});


   $('.drpd-ver > .label').on('click', function(event){
 event.stopPropagation();
   // Check if active class is there and remove it if it is
   if($( this ).hasClass( "active" )){
   $(this).removeClass('active');
   }
   else{
   // else just remove all other opened tabs and add the needed one
   $('.drpd-ver > .label').removeClass('active');
   $(this).toggleClass('active');
   }   
   });
  
  // removing active class if clicked anywhere else ?? 

});
body{
    background-color: lightblue;
}
.drpd-ver{
    position: relative;
    display: inline-block;
    font-size: 16px;
    color: #000;
    margin-left:400px;
}

/* Click to expand button */

.drpd-ver label{
    box-sizing: border-box;
    display: inline-block;
    width: 100%;
    background-color: #FFF;
    padding: 15px 20px;

    cursor: pointer;
    text-align: center;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);

    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;

    -webkit-transition: .2s;
    transition: .2s;
}


/*  The ul will have display:none by default */

.drpd-ver ul{
    position: absolute;
    right: 0;
    list-style: none;
    text-align: left;
    width: 200px;
    z-index: 1;
    box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.2);
    display: none;
    background-color: #DADADA;
    padding: 0;
}


.drpd-ver ul li{
    padding: 15px;
    background-color: #fff;
    color: #656565;
    font-weight: 600;
    margin-bottom: 1px;
    cursor: pointer;
}

.drpd-ver ul li:hover{
    background-color: royalblue;
    color: #FFF;
}

.drpd-ver ul li a{
    color: inherit;
    text-decoration: none;
}

/* Defining active states*/
.drpd-ver .label.active{
    background-color: royalblue;
    color:white;
}

.drpd-ver .label.active + ul{
    display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="drpd-ver">
    <span class="label">\/</span>
    <ul>
        <li><a href="#">Link One</a></li>
        <li><a href="#">Link Two</a></li>
        <li><a href="#">Link Three</a></li>
        <li><a href="#">Link Four</a></li>
    </ul>
</div>

Answer №2

One possible approach could be:

$(document).on('click', function(e) {
  if(!$(e.target).is('.dropdown-version > .label')) {
    // Here is where you can adjust classes or perform other actions
  }
});

Answer №3

To implement the removal of the active class in HTML when clicked, use the following code snippet:

$(document).ready(function(){
 $('html').click(function() {
 $('.drpd-ver > .label').removeClass('active');
});
   $('.drpd-ver > .label').on('click', function(event){
        if($( this ).hasClass( "active" )){
            $(this).removeClass('active');
        }
        else{
            $('.drpd-ver > .label').removeClass('active');
            $(this).toggleClass('active');
        }           
   });
});

Answer №4

   if ($(this).hasClass("active")) {
      $(this).removeClass('active');
    } else {
      // Toggle active class and handle click event
      $('.drpd-ver > .label').removeClass('active');
      $(this).toggleClass('active');
      var clickEvent = function() {
           $('.drpd-ver > .label').removeClass('active');
           $(document).off('click', clickEvent);
      };
      $(document).on('click', clickEvent);
      return false;
    }

Avoid turning off/on the click event by using a private variable.

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

Is it possible to implement Ajax functionality in JavaScript without using XMLhttp and connection the same socket for every request?

Can data on a page be communicated and updated without the need for reloading, all while avoiding the XMLHttpRequest object and using the same connection or socket for each request (without closing the connection each time)? ...

How to add a line break within the :after pseudo-element using CSS

I've been struggling to split text inside an :after pseudo-element of a label that receives its content from a data- attribute. I've attempted using word-break, as well as playing around with width, max-width, and position:relative, but nothing s ...

Locating the jQuery element just one element next to it

Having set up my HTML like this. <div id="wrap"> <div class="left"></div> <div class="right"> <a href="#">link</a> </div> <div class="listings" style="display:none"> <ul> ...

Bringing in More Blog Posts with VueJS

Exploring the Wordpress API and devising a fresh blog system. As a newbie to VueJS, I'm intrigued by how this is handled. The initial blog posts load as follows: let blogApiURL = 'https://element5.wpengine.com/wp-json/wp/v2/posts?_embed&p ...

adverse offset and backdrop

To achieve the desired layout, I am trying to adjust the negative margin for the .text div so that it aligns on top of the .image div. <div class="wrap"> <div class="image"><img src="imgage.jpg" /></div> <div class="text ...

Combine div elements with identical class

Is there a way to utilize jQuery in order to enclose groups of elements with the same class within a div? I have been searching for a solution, but haven't found one yet. Here's an example of the HTML: <div class="view-content"> < ...

Implement jQuery Tabs in Brackets software to enhance user experience

My Adobe Creative Cloud subscription is expiring soon, and I am considering switching to Brackets, an open-source code editor developed by Adobe. However, I am facing some difficulties adding jQuery tabs to my HTML documents. I downloaded the 1.10.4 zip f ...

Enhancing Your Website with Multiple Background Images in CSS3

Having trouble understanding how to position multiple background images with CSS3. I'm struggling to get them to display at the top, middle, and bottom of the page. Can you help me figure out how to make an image appear at different positions using a ...

How can I convert a string to an integer in Node.js/JavaScript in terms of cardinality?

Imagine a scenario where a user can input any string such as "1st", "2nd", "third", "fourth", "fifth", "9999th", etc. The goal is to assign an integer value to each of these strings: "1st" -> 0 "2nd" -> 1 "third" -> 2 "fourth" -> 3 "fifth" -&g ...

Encountered an error stating "Cannot access property FindAll() of undefined" while working with a node/express JS app

Hey everyone, I'm encountering a problem with my express JS application and I'm not quite sure how to fix it. I'm working with an existing mySQL db and attempting to fetch items from my tbl_person table in the myDB database. As a newbie to t ...

"Learn the process of converting a string to Time with the help of jQuery

I am working with a string that looks like this: "8:00 Am". My goal is to convert it into a time format using jQuery. Can anyone help me achieve this? ...

What is the best way to retrieve an ID from a select multiple using Element?

I am working on a select element for assigning persons to a project. My goal is to send the ID of the selected person object to a specific function. Here is what I have tried so far: <el-form-item label="Assign to:" prop="person"> & ...

Uploading data through AJAX without saving it in the database

Can someone please assist me? I am encountering an issue where I am uploading multiple data using an AJAX request. The data appears to upload successfully as I receive a response of 200 OK, but for some reason, the data is not being stored in the database. ...

Refresh a different Angular Controller after submitting a POST request

Just to clarify, I am looking to dynamically reload another controller with new data after a POST request without refreshing the page. Here is my code: No issues with saving data to the database. Script var app = angular.module('userBase', []) ...

What is the correct syntax for declaring a variable within a switch statement in TypeScript?

How can I properly use a switch statement in TypeScript to assign a new variable a value? For example: let name: string switch(index) { case 0: name = "cat" case 1: name = "dog" .... } I keep getting the err ...

Exploring the contents of this JSON array

I'm trying to fetch data from this link: <script type="text/javascript"> $.getJSON('http://api01.notaion.com/?item&id=120001462', function(data) { }); </script> I am uncertain whether I need to use a callback=?, a ...

The Body and HTML elements compress to sizes significantly smaller than the viewport

I am currently working on making my WordPress website responsive. On one of the pages, I have two images that I want to set a max-width of 100% to ensure they are responsive. However, when I shrink the page in Chrome dev tools, I noticed that the <html& ...

[CSS] What's the trick to getting it to smoothly glide to the top?

As a new designer, I have a question about how to make the background color extend to the top without any white space. Can someone please guide me on how to achieve this? <!DOCTYPE html> <html> <head> <style> body{ margin: 0px; p ...

Issue: The initial parameter should be a File or Blob object

Hey there! I'm currently utilizing the compressorjs plugin for compressing images, but I'm encountering an issue when selecting images. You can find out more about the plugin here. Here is my code snippet: window.resolveLocalFileSystemURL( ...

Navigate to the same destination with React Router Dom while passing state as a parameter

Let's talk about a scenario with a Link setup like this: <Link to={`/samelocation/${id}`} state={{ state1: 'hello' }}> This link is nested in a sub-component within the main component situated at /samelocation/:id. To ensure that the ...