Issue with dropdown list removeClass function

I am encountering an issue with the Jquery dropdown list click function. The addClass method is working properly, but the removeClass method is not functioning as expected. When I click on the dropdown list, it does not hide.

Here is a live demo: http://jsfiddle.net/wcbaxkdv/

Below is my code:

HTML:

<div id="dd" class="wrapper-dropdown-3" tabindex="-1">
   <span>WHERE DO YOU WANT TO GO?</span>
   <ul class="dropdown">
      <li><a href="#">WHERE DO YOU WANT TO GO?</a></li>
      <li><a href="#">addClass OK</a></li>
      <li><a href="#">WHERE DO YOU WANT TO GO?</a></li>
      <li><a href="#">removeClass Problem</a></li>
      <li><a href="#">WHERE DO YOU WANT TO GO?</a></li>
      <li><a href="#">WHERE DO YOU WANT TO GO?</a></li>
   </ul>
</div>

CSS:

.wrapper-dropdown-3 {
  background: none repeat scroll 0 0 #f0f1f1;
  border: medium none;
  border-radius: 0;
  box-shadow: 0 1px 1px rgba(50, 50, 50, 0.1);
  color: #8aa8bd;
  cursor: pointer;
  font-family: 'Archer-Book';
  font-size: 13px;
  font-weight: normal;
  height: 45px;
  margin-left: 25px;
  margin-top: 25px;
  outline: medium none;
  padding-left: 10px;
  padding-top: 15px;
  position: relative;
  vertical-align: middle;
  width: 87%;
}

/* Additional CSS rules omitted for brevity */

Js:

function DropDown(el) {
    this.dd = el;
    this.placeholder = this.dd.children('span');
    this.opts = this.dd.find('ul.dropdown > li');
    this.val = '';
    this.index = -1;
    this.initEvents();
}
DropDown.prototype = {
    initEvents : function() {
        var obj = this;

        obj.dd.on('click', function(event){
            $(this).addClass('active');
            return false;
        });

        obj.opts.on('click',function(){
            var opt = $(this);
            obj.val = opt.text();
            obj.index = opt.index();
            obj.placeholder.text(obj.val);
        });
    },
    getValue : function() {
        return this.val;
    },
    getIndex : function() {
        return this.index;
    }
}

$(function() {

    var dd = new DropDown( $('#dd') );

    $('.wrapper-dropdown-3 .dropdown li a').on('click', function() {
        // all dropdowns
        $('.wrapper-dropdown-3').removeClass('active');
    });
});

Answer №1

To prevent the dropdown from reappearing after being hidden, you must ensure that events do not bubble up from inner link elements a to div.wrapper-dropdown-3:

obj.opts.on('click', function (e) {
    var opt = $(this);
    obj.val = opt.text();
    obj.index = opt.index();
    obj.placeholder.text(obj.val);
    e.stopPropagation();  // <---- include this line
});

Check out a demo here: http://jsfiddle.net/wcbaxkdv/2/

Answer №2

Another option available is to utilize the toggleClass('active') function on the parent element (obj.dd). This allows users to close the menu by clicking on either the ul or a li item. The parent click event will still trigger and remove the handler in the end.

http://example.com/jsfiddle/

    function DropDown(element) {
        this.dropdown = element;
        this.placeholder = this.dropdown.children('span');
        this.options = this.dropdown.find('ul.dropdown > li');
        this.value = '';
        this.indexValue = -1;
        this.initializeEvents();
    }
    DropDown.prototype = {
        initializeEvents: function () {
            var object = this;

            object.dropdown.on('click', function (event) {
                $(this).toggleClass('active');
                return false;
            });

            object.options.on('click', function (e) {
                var option = $(this);
                object.value = option.text();
                object.indexValue = option.index();
                object.placeholder.text(object.value);
            });
        },
        getValue: function () {
            return this.value;
        },
        getIndex: function () {
            return this.indexValue;
        }
    }

    $(function () {

        var dropdown = new DropDown($('#dropdown'));

    });

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

Struggling to resolve issues with out-of-Viewport elements in my code while using Python 3.7 and Selenium

My current challenge involves troubleshooting my code to resolve the issue preventing me from utilizing the "actions.move_to_element" method to navigate to an offscreen element and click on it. The specific line of code I am focusing on is: Off_Screen_Ele ...

An issue occurred with player.markers not being recognized as a function when trying to utilize videojs markers

I am trying to add markers to my videojs player timeline. I have successfully implemented this feature a few months ago in a different project, but now when I try to use it again, I am encountering errors in the console and unable to see the markers on the ...

Using jQuery to load an image into a div and smoothly fade it in

I am currently working on creating a gallery and I am facing an issue with loading an image into a div. The problem arises when I try to apply a fade effect after the image has finished loading. If I remove the display:none property, the image does load in ...

What is the process for updating the dropdown list value based on the radio button that has been selected?

Is there a way to retrieve the value of a radio button and utilize it in the where clause? <input type="radio" name="radiobtn" value = "Yes" onclick="GetLockIn();" >Yes <input type="radio" name="radiobtn" value = "No" onclick="Ge ...

What sets apart a post API call from form submission using the post method?

Is it possible to call the payment gateway from Node.js using a POST API call? I understand that traditionally the payment gateway is called through form submission with the method set as post, which redirects to a new page. However, if I use a POST API ...

Is it possible to incorporate a jQuery widget within a table?

Can the jQuery sortable widget be utilized within a table, or is it designed to function separately? Here is the link to the jQuery widget for reference - http://jqueryui.com/sortable/#default ...

How can I apply both Css and Bootstrap styles to an element in Next.js?

I'm having trouble incorporating the Bootstrap class sticky-top into another CSS style element. I attempted to achieve the same effect without Bootstrap by adding position: sticky, top: 0 in the CSS, but it didn't work as expected. The issue aris ...

I'm receiving /generate_seeker/?complete_list=true, but what I actually need is /generate_seeker?complete_list=true

Check out this code snippet that utilizes axios in a React project. axios.get(`https://resolab-backend.herokuapp.com/core/create_seeker`,{ params:{ complete_list : true }, headers:{ 'Authorization': `Token ${cookies.get("token")}` } ...

Mastering Generic Types in Functions in Typescript

My current structure looks like this: export interface Complex { getId<T>(entity: T): string } const test: Complex = { getId<Number>(entity){return "1"} // encountering an error 'entity is implicitly any' } I am wondering w ...

Dynamic CSS sizing

Currently, I am in the process of creating a component and my goal is to achieve a specific layout without the use of JavaScript, preferably utilizing flexbox. Essentially, envision a messenger chat screen with a header and footer containing controls. htt ...

How can the event listener be utilized with md-autocomplete?

I am currently in the process of developing an angularjs application that incorporates an autocomplete feature. One key aspect of this application is that certain fields cannot be populated until an item has been selected using the autocomplete function. ...

Converting xpath location to pixels: A step-by-step guide

Is there a way to convert an Xpath location or an element ID into pixel coordinates (X,Y) using Java? I have searched extensively but have not been able to find a clear and simple answer. ...

Prevent web browsers from interpreting media queries

Creating a responsive website has been challenging, especially when it comes to accommodating IE7. I'm considering turning off ALL media queries for just IE7 while maintaining the styling and layout in desktop mode. Is this possible? ...

Automatically Adjust Text Size to Fit Input Forms using jQuery

Does anyone know how to use jQuery to dynamically change the font size in a form input field so that it always remains visible and fits even as the user types more text? I want the font size to start at 13px and progressively shrink as the text reaches the ...

When using the hasMany/belongsTo relationship in VuexORM, the result may sometimes be

I have carefully followed the documentation and set up 2 models, Author and Book. The relationship between them is such that Author has many Books and Book belongs to an Author. However, despite having the author_id field in the books table, the associatio ...

Does jQuery adhere to the 508 compliance guidelines?

I am currently developing a website using asp.net that must adhere to section 508 accessibility standards. I am unsure about whether I should incorporate JavaScript into the site. Is it permissible to utilize jQuery's slideUp()/slideDown() for displa ...

Is it possible to determine if a variable is unset using isset?

Currently, I am utilizing the following code snippet to verify if isset is not set. For instance: if(!isset($_REQUEST['search'])) { } else if(!isset($_REQUEST['submit'])) {} I would like clarification on whether !isset is considered ...

What is the best way to stop an embedded mp4 video from playing when a dynamically generated button is clicked?

After making modifications to the QuickQuiz code found at https://github.com/UrbanInstitute/quick-quiz, I have replaced the img with an embedded mp4 video that loads from a JSON file. Additionally, I switched from using the original SweetAlert library to S ...

Choosing an option from a PHP MySQL table based on a JavaScript value

I am attempting to create a select box that displays a value based on whether the database has a "yes" or "no" in the specified column. Despite my efforts, I am unable to identify any syntax errors causing this code snippet to not function properly. JavaSc ...

Overlapping Divs and Colliding Elements

I am currently exploring the moment when my two yellow divs will overlap and make contact with each other. It seems that the collision detection is triggering true even when the divs are not intersecting. If you'd like to take a look at the example, ...