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

When the screen size decreases, display the title on two lines

Currently, I am in the process of developing a react web application with the assistance of redux. My main objective is to ensure that the page is highly responsive. At this point, there is a title positioned at the top displaying: Actions to do: Past due ...

What is the best way to use jQuery to select a group of table rows based on the value of a

My current issue involves using a jQuery selector to move table rows "UP" and "Down." Here is the Table structure in HTML: jQuery Portion : $(".up,.down").click(function() { var row = $(this).parents("tr:first"); if ($(this).is(".up")) { ...

Iterating over images and displaying them in Laravel's blade templating engine, updating outdated Angular code

Currently, I am in the process of transitioning an Angular repeat function used for displaying images on our website (built with Laravel). The goal is to eliminate Angular completely and handle everything using Laravel loops in the blade template. I have ...

How come certain rectangles vanish when one rectangle completely fills the space?

Currently, I am encountering an issue with CSS paint worklet and I am trying to determine if it's a browser bug or an error on my end. In the worklet, I am drawing multiple rectangles. Strangely, when one rectangle covers the entire area, the others s ...

Loop through JSON array within an angular controller

I am currently attempting to iterate through a JSON array and display the values on the frontend of my application. I have provided my code, but I'm having trouble retrieving specific values (startDate, endDate) from within the array and displaying th ...

Ajax search implementation presents challenges in Laravel development

I have been working on my own custom PHP application. I'm trying to add a search feature using AJAX, but my code doesn't seem to be functioning correctly. index.php <?php if (isset($_POST['search'])) { // Perform search fu ...

Importing components in real-time to generate static sites

My website has a dynamic page structure with each page having its unique content using various components. During the build process, I am statically pre-rendering the pages using Next.js' static site generation. To manage component population, I have ...

Creating a repository of essential functions in AngularJSDiscover the steps to set up a

I am looking to create a set of reusable functions in AngularJS for CRUD operations that can be used across multiple entities in my project. I have already set up a factory using $resource for server communication, which looks like this: Model File: var ...

The body can only stretch up to a certain percentage of its width, not a full 100%

Recently, I've been encountering an issue with my webpage where the body does not stretch 100% the width of the screen. I've tried numerous CSS rules to fix it, but nothing seems to be working. When you view the page in a browser, it appears to c ...

What is the best way to utilize a portion of the data retrieved from an API call as the output for a function?

After extensive research and testing, I have been exploring ways to make API calls in node js. Currently, my focus is on utilizing a portion of the JSON object returned from an API call within a module to generate a Token. var request = require("request") ...

What is the best way to distribute components with varying cell heights?

I am currently working on creating a user interface layout with components that need to be arranged in a specific order, as depicted in the accompanying image. My task involves developing a Material UI Dialog within a React application based on the design ...

What is the best way to make ng-style append to a pre-existing style?

I am facing an issue with my custom popover directive and another custom directive that uses it. I am attempting to use ng-style to adjust the width of the popover. Below is a code snippet from the directive's html template: <div my-custom-popover ...

Trouble accessing data property within a method in Vue 3 with Typescript

I am facing an issue with accessing my data in a method I have written. I am getting a Typescript error TS2339 which states that the property does not exist in the type. TS2339: Property 'players' does not exist on type '{ onAddPlayers(): vo ...

Elements in table do not display properly in Internet Explorer

The alignment of the list element is off-center in Internet Explorer, whereas in Chrome it is perfectly centered. Below is a snippet of the code being used with the Bootstrap CSS Framework. Here is the JSfiddle https://jsfiddle.net/8cunpsvy/ ...

Looking for the top jQuery plugin for creating rounded corners on both divs and tables?

After experimenting with five different plugins, each with its own limitations, I'm still struggling to find one that meets my requirements. Specifically, I need a plugin that can round the corners of a div with a specified height, even if it has no c ...

Utilizing CSS to target the ID of an anchor element

I am a beginner in the world of HTML and CSS. I recently attempted to target an element using an id selector in my CSS code, but unfortunately, it did not work as expected. Can someone shed some light on why this might be happening? <!DOCTYPE html> ...

Storing information in the DOM: Choosing between Element value and data attribute

When it comes to storing values in a DOM element, we have options like using the data attribute. For example, $("#abc").data("item", 1) can be used to store values and then retrieve them with $("#abc").data("item"). However, I recently discovered that th ...

The form I created retrieves select options via an ajax call, but after saving, the post values are not displaying as expected

I have created a form with the following HTML code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Populate City Dropdown Using jQuery Ajax</title> <script type="text/javascript" src="h ...

I have tried to create two apps in AngularJS, but unfortunately, they are not functioning as expected

Having trouble with implementing 2 ng-app in a single html page. The second one is not working. Please review my code and point out where I am making a mistake. <div id="App1" ng-app="shoppingCart" ng-controller="ShoppingCartController"> &l ...

Dynamic dropdown menu selection and table display (PHP)

I've been working on building an Ajax / PHP grid that is based on a dropdown selection. The process starts with a dropdown select box on the page, where upon selection, a variable is passed to a PHP page. This PHP page then executes a select statemen ...