Issue with toggleClass being triggered twice while resizing browser window

I am currently in the process of creating a responsive navigation menu. I have completed the initial setup but encountered an issue while resizing the browser window. It appears that the toggleClass function is being triggered multiple times when I resize the browser. The strange thing is that upon refreshing the page, everything works fine, but when I try to resize the window, the toggle effect occurs multiple times with a single click.

Below is the code snippet that I have been working on:

JSFiddle - https://jsfiddle.net/kvpyzbxr/1/

<header>
    <ul class="navigation secondary-navigation">
       <li>
           Schools 
       </li>
       <li>
           Faculty
       </li>
       <li>
           Research 
       </li>
       <li>
           Contact Us
       </li>
    </ul>

    <ul class="navigation primary-navigation">
        <li>
            <a href="#">Programs</a> 
            <ul>
                <li><a href="#">Degree Programs</a></li>
                <li><a href="#">Master in Business Administration</a></li>
                <li><a href="#">Executive Master in Business Administration</a></li>
                <li><a href="#">Master in Entrepreneurship</a></li>
                <li><a href="#">Master of Science and Innovation and Business</a></li>
                <li><a href="#">Master in Development Management</a></li>
            </ul>
        </li>

        <li>
            <a href="#">Admissions</a>
            <ul>
                <li><a href="#">How to Apply</a></li>
                <li><a href="#">Application Form</a></li>
                <li><a href="#">Scholarship and Financial Aid</a></li>
            </ul>
        </li>

        <li>
            <a href="#">About Us</a>
            <ul>
                <li><a href="#">Why AIM</a></li>
                <li><a href="#">Leadership</a></li>
                <li><a href="#">Network and Alliances</a></li>
                <li><a href="#">Our Brand Story</a></li>
            </ul>
        </li>

        <li>
            <a href="#">News</a>
        </li>

        <li>
            <a href="#">Alumni</a>
            <ul>
                <li><a href="#">AIM Leader Magazine</a></li>
                <li><a href="#">My AIM Connect</a></li>
                <li><a href="#">Triple A Awardees</a></li>
            </ul>
        </li>

        <li>
            <a href="#">Give</a>
            <ul>
                <li><a href="#">Make A Gift</a></li>
            </ul>
        </li>
    </ul>
</header>

<script>

$(document).ready(function() {

    function detectMobile() {
        if ($(window).width() < 1080) {
            $('header').addClass('mobile');
            $('.secondary-navigation').insertAfter('.primary-navigation');
        }

        else {
            $('header').removeClass('mobile');
            $('.secondary-navigation').insertBefore('.primary-navigation');
        }

        $('.navigation li').on('click', function() {
            console.log('open');
            $(this).toggleClass('expand-menu');
        })
    }

    detectMobile();

    $(window).resize(function() {
        detectMobile();
    })


})


</script>

header {
  max-width: 1336px;
  margin: 0 auto; 
}

header .navigation {
  padding: 10px 0;
  clear: both; 
}

header .navigation li {
  padding: 10px;
  display: inline-block;
  position: relative;
  font-family: 'Arial', sans-serif;
  background-color: #272041;
  color: #fff;
  float: left; 
}

header .navigation li a {
  color: #fff; 
}

header .navigation li ul {
  position: absolute;
  top: 0;
  left: 0;
  padding-top: 30px;
  display: none; 
}

header .navigation li ul li {
  background-color: #231d39;
  color: #95939e; 
}

header .navigation li:hover ul {
  display: block; 
}

header.mobile .navigation li {
  display: block;
  float: none; 
}

header.mobile .navigation li ul {
  position: static;
  display: none;
  height: 0; 
}

header.mobile .navigation li.expand-menu ul {
  height: initial;
  display: block; 
}

Answer №1

The reason for the multiple click-events being added is due to repetitive calls of detectMobile(). Each time this function is executed, a new click event is bound to $('.navigation li'). To resolve this issue, simply place

$('.navigation li').on('click', function() {
     console.log('open');
     $(this).toggleClass('expand-menu');
})

outside of the detectMobile() function.

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

Troubleshoot: Why Your jQuery AJAX Post Requests Are Failing

I'm having trouble understanding why this code isn't functioning properly. Currently, the php function "alias_valid" is just returning a string temporarily for testing purposes, so I've omitted including the php function here. The alert mess ...

Unable to use the select function in Android 2.2

When I click on the select button in my app, it displays multiple options. This functionality works smoothly on Android 4.1, but on Android 2.2, clicking on the select button does not have any effect and therefore the options cannot be selected. <sec ...

Modifying the value of an element in an array of state variables

I currently have an array of objects stored as a state variable. My goal is to create a function that can modify a specific field within one of the objects. interface IItem{ id: string, selected: boolean } const [array, setArray] = useState<IItem[]&g ...

Aligning Pictures in My HTML Code

I am struggling to center images in my HTML code, as they are all aligned to the left. I'm working within Infusionsoft and have attempted various methods to center them without success. Not sure if it's a limitation of the system or if I'm m ...

Stop aspx button postback on click using cSharp

The following HTML code snippet includes an <asp:Button> element. <asp:Button ID="CalculateG481" runat="server" Text="Calculate" OnClick="CalculateG481_Click" /> When clicked, the button calls the function CalculateG481_Click but then initia ...

Jquery FullCalendar displaying incorrect date

I have recently set up a running jQuery FullCalendar and encountered an issue where the calendar is displaying the wrong day. Today is March 21, 2014 (Friday) but it is showing as Saturday (Sab in Italian). The version of FullCalendar being used is 1.6 (t ...

Designing a website using HTML and CSS with the goal of optimizing it to fill

My website includes all the recommended elements in the head area: <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, ...

Improving code quality and consistency in Javascript: Tips for writing better code

Hey, I've been experimenting with some code using ajax and have ended up with a lot of repetitive lines. Is there a way to streamline the code without losing functionality? I keep using the .done method multiple times when I could probably just use it ...

The call stack reached its maximum size while attempting to send a post request in an Express application

'Error Occurred: RangeError: Maximum Call Stack Size Exceeded' When Making a Post Request in Node.js with Express and body-parser As a beginner in the world of node.js, my journey took a challenging turn while following along with video #30 from ...

Focus on selecting just one button within Angular

By retrieving values from a database and displaying them using ng-repeat within a div: <div ng-controller = "myTest"> <div ng-repeat="name in names"> <h4>{{name.name}}</h4> <button ng-class="{'active ...

Simple method for validating a text box field using jQuery without the need for a form

I am looking for a way to activate jquery unobtrusive validation without a form using the specified pattern: <script type="text/javascript"> $('.btnAddAsync').click(function (e) { e.preventDefault(); // Avoid href p ...

Finding maximum values by key in Mongoose

Welcome to My Schema let schema = new mongoose.Schema({ property: String, numericValue: Number }, { timestamps: true }); In my database, I store various statistics like: let entryA = { property: "visitors", numericValue: 120 } let en ...

How to redirect to a different view or controller using ASP.NET and AngularJS

How can I open the View located at /Home/CreateItem after clicking on the Add button? What do I need to include in my code? $scope.Add = function() { console.log('working'); } This is how Index.cshtml looks like: <script src="~/ ...

Angular2 - Incorporating a New Attribute

I am working with the following Angular2 code: <ngx-datatable-column prop="id" name="ID"> <template ngx-datatable-cell-template let-row="row" let-value="value"> <a [routerLink]="['/devicedtls',r ...

How to dynamically assign a value to ng-click directive in AngularJS

Is there a way to dynamically set a value into ns-click? For example: <td ng-click="{{schedule.action}}" ng-init="schedule.action=schedule.action" ng-repeat="schedule in room.Schedule">{{schedule.firstName}}</td> I encountered the following e ...

Facing difficulty in uploading image to local server using Froala editor

For testing purposes, I've been attempting to upload images using the Froala WYSIWYG editor on my localhost, but unfortunately, it's not functioning as expected. After selecting an image to upload, it briefly appears faded in the editor and then ...

Unexpected JSON response generated by my PHP script following an AJAX request

I'm still learning and I seem to be making a mistake somewhere. I have a PHP result set that I need to iterate through, like this: $rows = array(); while($r = mysql_fetch_assoc($result)) { $rows[] = $r; } echo json_encode ...

Clicking the save button in the modal updates the text on both the current tab and any previously clicked tabs

I'm looking to implement tabs that, when clicking on the edit icon, open a modal for editing the content of each tab. The issue I'm currently encountering is that if I open the editor for one tab, close it without saving, then open the editor fo ...

Can the default jQuery mobile ajax loader be triggered automatically when making a $.post() call?

Similar Question: Displaying Spinner on jQuery Mobile Ajax Call Is there a way to automatically trigger the default jquery-mobile ajax loader when using $.post()? For example, can I set up a global configuration for this behavior? I came across this ...

Once a value is selected from the datalist input autocomplete, it loses focus

My issue involves using an input with a dynamic datalist for auto completion. To achieve this, I've implemented the following approach: A key function in my process is as follows: $(function () { $("#to").on("input", function (e) { ...