The jQuery dropdown menu smoothly expands to reveal all hidden submenu options

I'm currently encountering an issue with jQuery. I am trying to create a responsive drop-down menu with sub-menus. The behavior I want is that if the window width is less than 700px, the submenus will trigger onClick. And if the window is wider than 700px, the submenus will be triggered onHover.

The window resize code is in place to facilitate changes when resizing the window without needing to refresh the page. It functions correctly, but the problem arises when clicking/hovering on any of the two links with nested sub-lists; it opens ALL the nested lists instead of just the one clicked on. Apart from this issue, everything else works as intended.

Here is the HTML code (with the .navLevel2 class having display: none):

    <div class="mainNav">
     <ul class="navLevel1">
    <li><a href="">link 1</a></li>
        <li class="fakeLink">link 2
           <ul class="navLevel2">
            <li><a href="">link 2.1</a></li>
        <li><a href="">link 2.2</a></li>
           </ul>
        </li>
        <li class="fakeLink">link 3
           <ul class="navLevel2">
            <li><a href="">link 3.1</a></li>
                <li><a href="">link 3.2</a></li>
           </ul>
        </li>
        <li><a href="">link 4</a></li>
      </ul>
    </div>

And here is the jQuery code:

    <script>
      $(document).ready(function(){
        function checkWidth() {
            var windowsize = $(window).width();
            if (windowsize < 700) {
                $('.navLevel1').addClass('small');
                $('.fakeLink').attr('onclick','return click_m()');
            } else {
                $('.navLevel1').addClass('big');
                $('.fakeLink').attr('onmouseover','return toggle_m()').attr('onmouseout','return toggle_m()');
            }
        }
        checkWidth();  // Execute on load

        $(window).resize(function() {
            if($(window).width() < 700) {
                $('.mainNav > ul').removeClass('big');
                $('.mainNav > ul').addClass('small');
                $('.fakeLink').attr('onclick','return click_m()');
                $('.fakeLink').removeAttr('onmouseover','return toggle_m()').removeAttr('onmouseout','return toggle_m()');
            }
            else if($(window).width() > 700) {
                $('.mainNav > ul').removeClass('small');
                $('.mainNav > ul').addClass('big');
                $('.fakeLink').attr('onmouseover','return toggle_m()').attr('onmouseout','return toggle_m()');
                $('.fakeLink').removeAttr('onclick','return click_m()');    
            }
        }) // window.resize
      }) // document.ready
    </script>

The triggers defined in the header:

function click_m(){
  $('.fakeLink > ul').slideToggle(300); 
}

function toggle_m(){
  $('.fakeLink > ul').stop().slideToggle(300);  
}

My issue now is: When hovering/clicking on Link 2 or Link 3, it opens ALL the nested lists simultaneously. I am struggling to identify the root cause of this bug. Your help would be greatly appreciated!

Thank you!

Answer №1

It might be helpful to update your click_m function to specifically target the element that is being clicked. Here's an example of how you could do this:

function click_m($target){
  $($target).children().slideToggle(300); 
}

Then, in your script, you can use the following code:

$('.fakeLink').attr('onclick','return click_m(this)');

This method appears to be successful. You can view a demonstration here: Codepen Example

You can apply a similar approach for hover interactions as well.

Answer №2

When using the selector .fakeLink > ul in your function -

function click_m(){
   $('.fakeLink > ul').slideToggle(300);   
}

function toggle_m(){
   $('.fakeLink > ul').stop().slideToggle(300);  
}

This will search for all <ul> elements within the class .fakeLink and display them all.

To target only the next <ul>, you can utilize the next() method like this:

function click_m(){
   $('.fakeLink').next('ul').slideToggle(300);   
}

function toggle_m(){
   $('.fakeLink').next('ul').stop().slideToggle(300);  
}

Note that this code has not been tested yet.

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 an array of a specific field within a JSON string using the collect() method of objx is a straightforward process

Here is the JSON string I am working with: var data = [{"first":"3","second":"1"},{"first":"5","second":"5"},{"first":"7","second":"1"}]; Currently, I am using the following code - objx(data).collect("first") I am expecting to receive an array like [3 ...

Finding a nested div within another div using text that is not tagged with XPath

I need help creating an XPath to select a div with the class "membername" using the parameter "Laura". <div class="label"> <div class="membername"></div> David </div> <div class="label"> < ...

update embed - new command

My code below creates a slash command and I'm attempting to update the embed every 10 seconds. const embed = new EmbedBuilder() .setAuthor({ name: track.title, iconURL: client.user.displayAvatarURL({ size: 1024, dynamic: true }) }) .setThumbna ...

Moment JS initialization and the utc() function

I am trying to comprehend the way Moment JS initializes its moment object. For instance, let's say I want to create a moment for the date and time: April 1, 2000, 3:25:00 AM with a UTC offset of +8 hours from UTC/GMT. To represent this in JavaScript ...

Having trouble with loading image textures in three.js

Here is the code snippet I am using: var scene = new THREE.Scene(); // adding a camera var camera = new THREE.PerspectiveCamera(fov,window.innerWidth/window.innerHeight, 1, 2000); //camera.target = new THREE.Vector3(0, 0, 0); // setting up the renderer ...

The JSON response from Rails containing multiple lines is not being parsed accurately

I am currently working on a Rails application with a json response using show.js.erb. { "opening": "<%= @frame.opening %>", "closing": "<%= @frame.closing %>"} An issue I encountered is that when @frame.opening contains multiple lines, jQuer ...

Embed a PHP function within an HTML tag using the echo statement

I have a unique function in my controller that retrieves the User's name here: public function fetchUser(){ $user_id = $this->session->userdata('ID'); return $this->users_model->get_user_name($user_id); } My goal is ...

Ensure that the array in Jest does not have any falsy values present

Attempting to utilize Jest for a unit test to ensure the absence of falsy values in my array named values. Unfortunately, the initial approach is not effective; the test actually passes: const badValues = ['', null, undefined, false, {}, []]; e ...

Smooth Div Scroll experiencing display issues

Trying to integrate the smooth div scroll, specifically the "Clickable Logo Parade" found at: Successfully implemented it on a blank page exactly as desired, but encountering issues when inserting it into the current layout. Could something be causing int ...

Creating virtual hover effects on Android browsers for touch events

My Wordpress website is currently utilizing Superfish 1.5.4 to display menu items. The menu on my site includes several main menu items, which are clickable pages, and hovering over these main items should reveal sub-menu options. When I hover over a mai ...

Display the output of awk on a single line for specific columns

Here is a file called "test" that displays the following information: vserver share-name path acl TEST_SERVER TEST_SHARE_PATH /TEST/TESTSHAREPATH "test\testuser / Read","test\testuser1_R / Read","test\testuser2_RW / Change ...

Creating multi-level nested lists with numbering using HTML and CSS

Is there a way to create a unique numbering format using only HTML and CSS lists (<ul> or <ol>)? 1. Item A 2. Item B 3. Item C 3.1. Subitem C.1 3.2. Subitem C.2 3.3. Subitem C.3 4. Item D 4.1. Subitem D.1 4.1.1 Sub-subi ...

What are some ways to stop WordPress from requesting jQuery from a different IP address?

My WordPress website has been infected with malware. I have discovered malicious code attached to the end of every jQuery script in all JS files. Additionally, there are multiple suspicious requests being sent to unknown hosts or IPs. I am struggling to i ...

Guide to making a leaf node with jstree version 3.0.0

The tree functionality seems to be functioning correctly, however, I am facing an issue with creating a leaf file. Although it is able to create a folder file, the creation of a leaf file seems to be problematic. Below is the code snippet that I am strugg ...

Guide on how to display registration form data on the current page as well as on a separate page

I am facing an issue with outputting registration form data to two different pages after successful validation. Specifically, I want the form data to be displayed on both the current page (form.php) and another page (profile.php). Despite my efforts to fin ...

React input field keeps losing focus during re-render operations

My current project involves using React to create an input text that displays a value from an in-memory data store and updates the store when the input value changes, triggering a re-render. However, I am facing an issue where the input text loses focus du ...

The post method is functioning properly in browsers such as Firefox, Internet Explorer, and Chrome; however, it is not working in the Edge browser

I am encountering an issue with a post method in the Edge browser. Even though I am able to receive responses for the same request in other browsers like Internet Explorer, Chrome, and Firefox, Edge seems to be not responding at all. Despite conducting a s ...

The height of the div element is causing issues for the adjacent item in the row

I am facing a styling issue where the height of my avatar image is affecting other inline items located next to it. The images below demonstrate this problem. As you can see, when I increase the height of my avatar logo, it causes the navigation links to ...

How to transfer a PHP echo value to a popup modal box

I am currently developing a web backend for a restaurant that includes functionality to block or unblock restaurant owners. I have implemented an "if" condition to display a button (a tag) based on the status of the restaurant owner. My goal is to pass the ...

Creating a Clickable SVG Element in React

I've been attempting to set up an onClick event in React, specifically within an SVG that includes multiple circle objects. However, when using "onClick," I'm encountering a strange issue: Upon data load, the onClick event is triggered six times ...