Jquery Toggle not applying class change on mobile devices

Check out my website: . There's a menu option called Services with a dropdown feature. Here is the code for it:

<li class="dropdown menu-services"><a class="dropdown-toggle" href="#" data-toggle="dropdown" data-target="#">Services <b class="caret"></b></a>
<ul class="dropdown-menu">
    <li class="menu-online"><a href="http://annapiotrowski.com/online-health-coaching/">Online</a></li>
    <li class="dropdown menu-in-person"><a href="#">In Person</a>
<ul class="dropdown-menu">
        <li class="menu-classes"><a href="http://annapiotrowski.com/classes/">Classes</a></li>
        <li class="menu-corporate-wellness"><a href="http://annapiotrowski.com/corporate-wellness/">Corporate Wellness</a></li>
    </ul>
</li>
</ul>
</li>

If you're on mobile, clicking on Services should expand the menu to display the items in the dropdown. I'm using this jQuery script to toggle it:

<script>

(function($) {

    $(document).ready(function(){

        var newWindowWidth = $(window).width();
        if (newWindowWidth < 768) {

        $(".dropdown").on("click", function() {

        $(".dropdown").toggleClass("open");


        });

        }

    });

})( jQuery );

</script>

When the page is at the top, I can click on the Services menu item and see the dropdown items.

But when I scroll down and try to do the same mid-page, it doesn't work at all :( Clicking on Services does nothing. What could be the issue?

I've attempted this fix:

(function($) {

    $(document).ready(function(){

        var newWindowWidth = $(window).width();
        if (newWindowWidth < 768) {

        $(".dropdown").on("click", function() {

        $(".dropdown").toggleClass("open");


        });

        $(".dropdown").off("click").on("click", function() { $(".dropdown").toggleClass("open"); });

        }

    });

})( jQuery );

Still no luck.

Answer №1

In order to properly identify the target of a click event, it is recommended to use the "context" keyword within the click handler function. I have optimized your click handler code below and tested it successfully on your website:

 $(".dropdown").off("click").on("click", function() {
    $(this).toggleClass("open"); 
    $(this).find(".dropdown").toggleClass("open");
 });

Answer №2

In the event that you are using a mobile device, it seems like the issue arises from having two menu elements in the document.

If you find yourself at the top of the page, try clicking on the Services menu item (it should function properly) and keeping it open as you scroll down. This way, you will be able to view the second menu element as you continue scrolling.

You just need to make some adjustments to your JavaScript code to accommodate the second menu.

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

How can you give a div a background without any text inside?

I am struggling to create an HTML element with a background image using CSS, but the background does not show up unless there is text inside the element. CSS - #box { background:url(.....) } HTML - <div id="box">something</div> // this w ...

Prevent the row height from fluctuating following the fadeOut() effect

Currently, I am facing an issue with two elements on my page: .start_over_button and .speed_buttons. In CSS, the .start_over_button is set to display: none, and in my JavaScript code, I have it so that when .speed_buttons are clicked, they fade out and the ...

Tips on adjusting the font size of headers in a Vuetify v-data-table?

I've been struggling to change the font size of the headers in my v-data-table. No matter what I try, the font doesn't seem to update. I even experimented with the Chrome developer tool and managed to make it work there. However, when I attempt t ...

What is the best way to achieve a full width table in an HTML format on a smartphone browser?

Apologies for my limited English proficiency. I am currently working on creating a horizontal scrollable table in HTML. My goal is to make the width of the table span beyond the browser's viewing area, so that sticky cell functionality can be implem ...

Ways to display a div when a drop-down box is clicked

How can I make a dropdown box that displays 'Yes' and 'No' options? When 'Yes' is selected, how do I show another div on the page? ...

The naming convention for CSS classes could be defined as follows: .sa-list li a > div{

As I dive into a CSS example, one particular section of code catches my eye: .sa-list li label > span, .sa-list li h3 > span, .sa-list li h4 > span, .sa-list li a > div{ position:relative; display:table-cell; vertical-align:middle; ...

transferring information between two ajax calls upon completion of the first ajax request

Attempting to pass data to jvectormap from an ajax call, using a when function to ensure the code runs after the ajax call has finished loading. The issue I'm facing is that the map appears empty and I encounter an error. Uncaught ReferenceError: ...

Prevent reloading the page when adding a flash element using JavaScript (jQuery)

Here is the function I am working with: function onVideo(vchat, idUser){ $('#videollamada').html('<div class="videollamada">'+ '<div align="right">'+ ...

The footer is not being properly pushed down by the DIV

I created a page and utilized toggle with jQuery. The layout of my page is great, but when clicking on the button to reveal content, the div remains fixed and my content expands and hides behind the footer. Take a look at the image here: https://i.stack.i ...

I've been working on a script in JavaScript to retrieve lectures for a specific day, but I'm having trouble connecting my jQuery code to it

Exploring a JavaScript function that retrieves today's lectures for a specific section of a class using jQuery. The challenge lies in implementing this array of classes on an HTML file. //function to get today var today = new Date(); var dd = today ...

The modal remains visible

Has anyone encountered a problem with hiding a Bootstrap modal based on form validation in JavaScript? I'm facing an issue where the submit function is not executed when I click the button. I've attempted using onsubmit=validateForm(), but it doe ...

Clicking on an anchor tag will open a div and change the background color

.nav_bar { background: #c30015; margin-left: 50px; float: left; } .nav_bar ul { padding: 0; margin: 0; display: flex; border-bottom: thin white solid; } .nav_bar ul li { list-style: none; } .nav_bar ul li a { ...

Is it possible to identify when an element has scrolled out of view just one time?

In an attempt to determine if an element has been scrolled out of view, I have implemented the following code: $(window).bind('scroll', function(){ var $btn = $('#intro div.summary a[href=#top]'); if($(window).scrollTop() > ...

Align the checkbox input in the center of a flexbox container

I am in the process of creating a side menu with filters, and I need to design a row that includes an input checkbox along with some accompanying text. However, I am facing an issue where the checkbox does not center properly within the flex container when ...

Chrome hanging after AJAX delete operation has been executed

After conducting a same-origin AJAX delete using jQuery, any subsequent calls made by the same client to the server are getting stuck. The specific issue is outlined below. Can you please review and let me know if there's something incorrect, as this ...

Issues arising when checking the responsiveness of the navigation bar on display

Recently, I encountered an issue with the navigation bar on my webpage. It contains an image logo on the left and three links on the right. The problem arises when I test the responsiveness using different devices on Chrome; the navigation bar resizes and ...

Is there a way for me to easily showcase a randomly selected product from my database in a box on my website

For my Rails 3.0 project, I am considering building a partial that refreshes periodically to display products from a list using jQuery. Is this the recommended way of doing it in the Rails framework? ...

I have to ensure that a plugin is only loaded once its dependency has been loaded with RequireJS

Currently, I am utilizing the jquery.validationEngine.js plugin and facing an issue. It seems that jqueryValidateEnglish is unable to function properly unless jqueryValidateEngine is loaded beforehand. In my code for jquery.wrapped.validationEnglish2.js, ...

Utilizing JSON with JQueryUI autocomplete in a Ruby on Rails environment

Hello everyone, I am currently working on an autocomplete form field and I seem to be having some trouble formatting the JSON data that needs to be passed into it. The JSON is returning in the following format: {"users":["12345","23456","34567", ... ]} ...

Utilizing Jquery queue for running a series of Ajax requests; imperative to clear the queue in case of a failed request

I am currently working on creating a queue of ajax calls that need to be executed in order. The process seems to be functioning properly, but I am encountering an issue when there is an error in one of the calls. My goal is to stop the queue after an error ...