Struggling to close the dropdown with jquery

Check out this code snippet: https://jsfiddle.net/rajat_bansal/rtapaew5/1/

The jQuery section below is causing some trouble:

$(document).ready(function(e) {

        $(".sub-handle").click(function() {
           if(!$(this).hasClass('showing-sub')){ 
            $(this).find(".submenu").addClass('showing-sub');
            $(this).addClass("sidebarElementDivOnClick");
            $(this).find("a").addClass("outerMenuItem");
          }
          else{ 
              $(this).find(".submenu").removeClass("showing-sub");
         }
      });

      $(".innerMenuItem").click(function(){
       $(this).toggleClass("innerMenuItemOnClick");
      });
    }); 

I'm having difficulty removing a class with this code. It might be a small issue as I am new to jquery. Any assistance and explanation would be highly appreciated. Thank you!

Answer №1

You were looking at the wrong element to find the class. I made sure to include the necessary code to remove the classes when the menu is closed.

$(".sub-link").click(function() {
    if(!$('.submenu').hasClass('showing-sub')){ //class is not present, so add it and display dropdowns with specific backgrounds
        $(".sub-handle").find(".submenu").addClass('showing-sub');
        $(".sub-handle").addClass("sidebarElementDivOnClick");
        $(".sub-handle").find("a").addClass("outerMenuItem");
    } else { //if class exists, it means it was clicked again
        $(".sub-handle").find(".submenu").removeClass("showing-sub");
        $(".sub-handle").removeClass("sidebarElementDivOnClick");
        $(".sub-handle").find("a").removeClass("outerMenuItem");
    }
});

I have made modifications to your code, accessible here.

Answer №2

There is an incorrect condition in your jQuery code:

The correct conditions should be:

if(!$(this).find(".submenu").hasClass('showing-sub')){

OR

if(!$(this).hasClass('sidebarElementDivOnClick')){

Here are the examples to check: Example 1 and Example 2

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

Creating a website without access to the internet

When I'm working on my laptop in locations without internet access, I need to build a website. How can I assess the progress of my pages without an active browser? ...

CKEditor's height automatically increases as the user types

I am using a ckEditor and looking for a way to make its height automatically grow as I type. https://i.stack.imgur.com/m7eyi.png <textarea name="description" id="description"> </textarea> <script> CKEDITOR.replace( 'description ...

Enhance the speed of AJAX search within a UL LI list containing over 5000 objects

Dear Stack community, I've been working on a simple Ajax js search using .addClass and .removeClass as I discovered it's faster than using .show() and .hide(). However, the speed is still not up to par and I'm feeling quite lost. You can ...

Retrieve data from database using SQL Injection tactics

I'm working on a website where I need to access a password. The page only has one form where the password can be entered. I attempted using "OR 1=1# and it showed "Authentication valid", but it didn't actually provide me with the password I was ...

A Step-by-Step Guide on Sending Response to ajaxError Callback in Perl

When working with JavaScript, I have a method of capturing errors that looks like this: $(document).ajaxError(function(event, jqxhr, settings, thrownError) { handleError(MSG_SAVE_ERROR); }); Now, my question is how can I retrieve an error message fro ...

Update the image when the radio button is chosen

I've customized two radio buttons by hiding the input marks and replacing them with images: <div class="card-block center-style"> <div class="form-check inline-style"> <label class="form-check-label question-label"> ...

PHP failing to send emails from my website

My website has a contact form, but the form data is being appended to the URL and the JSON is not being sent to the PHP mail handler. Below you can find my code for the form. HTML <form novalidate="novalidate" style="width:60%;margin-left:auto;margin- ...

What is the process for transforming information from a database into a clickable hyperlink?

My course list includes the following: SE1111 SE2222 SE3333 I want to display this list on my webpage and have it redirect to a page where the course name is saved for future use. Here's what I've tried so far: <div id="join_courses" clas ...

Ways to retrieve the previously selected option in a dropdown list

I am working with a form that includes a dropdown list featuring options such as apple, gova, lemon, and more. Each option has an associated counter - for example, apple=5, gova=3, lemon=6. If I initially select apple from the dropdown, the count for apple ...

Guide to configuring an Angular Material Footer using Flex-Layout

Could someone help me with setting up the footer in my Angular Material app? I want it to: stick to the bottom when the content height is smaller than the view-port move down or get pushed down when the content height exceeds the view-port One important ...

After pressing submit, any associated links should automatically open in a separate tab

I have a homework assignment that requires creating a form with multiple elements, including a checkbox. Once this checkbox is checked, the links displayed on the resulting page should open in a new tab. The catch? I can only use HTML and CSS - no JavaScri ...

Using Jquery to eliminate the selected option from the second dropdown list after choosing from the first

Currently, I have implemented this code to enable me to choose an item from dropdown 1 and then remove the same item from dropdown 2. $("#BoxName").change(function(){ var selectedItem = $(this).val(); var nextDropdown = $(this).parent("td").nex ...

What is the benefit of utilizing pseudo elements to divide block elements?

I'm seeking clarification on a w3school example that showcases responsive grid design. <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> * { box-sizing: bo ...

extracting ID values from a looped table with the use of PHP and JavaScript

I've been experimenting with PHP and MySQL to create a table, here's what I have so far... PHP :- foreach($result as $res){ echo '<tr><td style="display:none;"><p id="ID">' . $ID . ' </p></td&g ...

Hyperlinking Github.io Images

I'm facing an issue regarding image paths on github.io. It seems like the images from my github repository are not displaying properly (I made sure to check spelling and case sensitivity). I'm running out of ideas, so maybe you can help me spot m ...

Numerous lists conveniently consolidated within a single navigation bar

I am currently exploring the functionality of StumbleUpon's navigation bar by attempting to replicate it. My approach involves using 3 lists within 1, structured like this: <nav role="navigation"> <ul id="rightnav"> & ...

With every item retrieved by

After retrieving each element from the list of followers, a checkbox is generated. When the submit button is clicked, I aim to identify which checkboxes are checked and which are not. {! insert code here } Is there a way to capture the values of these ch ...

The body tag mysteriously disappears after the function is called within the $().html() command

As I delve into scraping the source code of a website, I encounter an interesting phenomenon. Initially, when I print out the complete source code, everything appears as expected. However, upon attempting to print an actual DOM, I notice a slight change i ...

Ways to activate jQuery validation when submitting a form instead of triggering it on blur

I am currently utilizing the Jquery Validation plugin to validate form fields upon submission. However, I have encountered an issue where incorrect email format triggers a validation message when moving to the next input field. This behavior is undesirable ...

I'm curious about where to find more information on this new technology called the 'scroll to page' feature

Recently, I came across a captivating website feature that caught my eye. As someone relatively new to front end web development, I am intrigued by the scrolling technique used on this site. I'm specifically drawn to the 'page to page' scro ...