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

A guide on utilizing setTimeout for repeatedly executing a function

I am facing an issue with my slideshow containing 4 pictures and pagination. I want the pictures to be displayed one by one in a loop, so I tried using the following code: function displayPictures(intervalTime) { setTimeout('$("#picgallery_pagging li ...

Leveraging the power of Material-UI and React, modify the appearance of the "carrot" icon within the

Currently implementing MUI's textfield based on the information found at this link: https://mui.com/components/text-fields/. While there are numerous resources available for changing the font of the input text, I have not come across any documentation ...

Can you provide instructions on integrating bootstrap 5.02 using npm and webpack?

Trying to bundle my webapp with webpack, but struggling with importing the bootstrap code. I've already spent hours troubleshooting this. Ever since setting up webpack, things haven't been working as they did before. And now, I keep encountering ...

Bringing in a feature within the Vue 3 setup

At the moment, I am attempting to utilize a throttle/debounce function within my Vue component. However, each time it is invoked, an error of Uncaught TypeError: functionTD is not a function is thrown. Below is the code snippet: useThrottleDebounce.ts imp ...

The struggle of accessing child components using ViewChild in Angular

I am facing an issue with a dialog box that is supposed to display a child component separately. Below is the code for the child component: @Component({ selector: 'userEdit', templateUrl: './edituser.component.html', styleUrls: [ ...

Representation of a family tree in CSS showcasing multiple sub-parents (both many to one and one to many relationships)

I've come across various family tree presentations. I'm curious if it's possible to display a one-to-many and then many-to-one structure? Currently, the flow is linear stop after stop, but I'd like to incorporate multiple steps that con ...

Utilizing AngularJS within a Captive Network Assistant (WISPr) on iOS and MacOS devices

In my past experiences with projects, it has been observed that Apple's Captive Network Assistant (also known as WISPr client) operates with a restricted browser. For further information, you can refer to How can I debug the browser in Captive Portal? ...

Troubleshooting problems with AngularJS loading data through ajax

One of the custom widgets in my application relies on Angular functionality. On a particular page, this widget is loaded via ajax. The following content is fetched through ajax and inserted into the DOM: _abc.html: <script type="text/javascript">c ...

originalRenderPage has not been declared

I encountered an issue while working on my new nextjs app. The problem arose when I tried to add a carousel using props in my project, resulting in an error stating that 'originalRenderPage' in Document.js is not defined. Any assistance would be ...

Is there a way to adjust the positioning of an image within a <div> element?

I'm attempting to vertically align an image within a horizontal menu bar. My goal is to adjust the padding/margin of the image using inline CSS. However, I've noticed that when I add margin-top or padding-top, it affects the positioning of all m ...

Floating CSS containers

Apologies for not including a picture. You can view the design I am trying to achieve here. I am attempting to create two boxes with a third box below them, and another box on the right side of the layout. All enclosed within a larger container. Everythin ...

What enables typescript to be eligible for transpiling is its equivalent level of abstraction to javascript?

Transpilation is the act of converting code from one language to another with a similar level of abstraction. Can you point out some distinctive characteristics that indicate TypeScript transpires into JavaScript? ...

Ways to deselect a checkbox if the selected option is anything other than 'All'

I have a set of checkboxes generated from a database, but one checkbox labeled "All" serves as a way to select or deselect all other checkboxes with a single click. If all the options are checked and any individual option (other than 'All') i ...

Shut down the popup window

I am diving into the world of jQuery and have successfully created a popup window with a button. However, I am encountering an issue where clicking on the button does not close the popup window as intended. Any guidance or assistance would be greatly app ...

Complete my search input by utilizing ajax

It's only been 30 minutes since my last post, but I feel like I'm making progress with my search posts input: I've developed a model that resembles this: function matchPosts($keyword) { $this->db->get('posts'); ...

Integrate an item into the request body utilizing the $.load() function in jQuery

Currently, I am using a POST request via jQuery's $.load function to retrieve data to display in a window. This is what I am currently doing: var testObject = { thing1: 'data1', thing2: 'data2', thing3: &a ...

Can you explain the error message "a.split is not a function" in an Angular context?

My Angular application is encountering an error upon page load. The error message displayed is as follows: angular-amin.js:122 TypeError: a.split is not a function at r (angular-amin.js:186) at m.$digest (angular-amin.js:145) at m.$apply (angular-ami ...

The issue with Node.js router failing to process delete requests

My Node.js router is handling all methods well except for the DELETE method. I can't figure out why the delete request does not reach the router. The AJAX request seems to be functioning correctly. AJAX request: function ajaxHelper(url, onSuccessAr ...

obtaining the controller output in JavaScript

Scenario: Retrieving id in javascript following an ajax post I'm trying to figure out how to access the id sent from my controller's ActionResult in javascript. I've experimented with both Content Result and JSON Result on the controller, b ...

Hide the border below the active tab

Could anyone assist me in removing the border below the selected tab? I've attempted multiple approaches without success. I experimented with adding a negative margin to the tab and creating a white border, but as the border I want to conceal is from ...