Toggle sliding in an open or closed direction indefinitely

Currently facing an issue where a menu should open/close on mobile devices. To achieve this, I have implemented an if-statement to check the browser width and execute a script accordingly:

$(window).resize(function() {
  var mobilewidth = $(window).width();
  if(mobilewidth < 873 ) {
    $(".mod_customcatalogfilter h2").click(function() {
      $(".filterform").slideToggle();
    });
  } else {
    $(".filterform").removeAttr("style");
  }
});

Although it is functional, the .filterform seems to be bouncing up and down before closing.

To see the issue in action, please visit: http://codepen.io/Sukrams/pen/WwjejP

If anyone has any insights as to why this behavior occurs, your input would be greatly appreciated.

Answer №1

Each time the event is bound on resize, adding another actionListener without overriding the existing one. To improve performance, consider unbinding the event each time.

if(mobilewidth < 873 ) {
    $(".mod_customcatalogfilter h2").unbind();
    $(".mod_customcatalogfilter h2").click(function() {
        $(".filterform").slideToggle();
    });
} else {
    $(".mod_customcatalogfilter h2").unbind();
    $(".filterform").removeAttr("style");
}

A more efficient approach would be to cache variables and bind the event only once.

var $filter = $(".mod_customcatalogfilter h2");
var mobilewidth = $(window).width();
$filter.on('click', function() {
    if (mobilewidth < 873) {
      $(".filterform").slideToggle();
    } else {
      $(".filterform").removeAttr("style");
    }
});
$(window).resize(function() {
  mobilewidth = $(window).width();
});

Answer №2

Whenever the window is resized, a new click event listener is generated. This means that each time you click, the event listeners will be triggered x times (as many times as the window has been resized under 873 pixels). Therefore, the solution should ensure that the event listener for click is not created multiple times.

One way to achieve this is -

var isEventListenerCreated = false;
$(window).resize(function() { 

    var mobilewidth = $(window).width();

    if(mobilewidth < 873 && !isEventListenerCreated) {
       isEventListenerCreated = true;
        $(".mod_customcatalogfilter h2").click(function() {
            $(".filterform").slideToggle();
        });
    } else {
        $(".filterform").removeAttr("style");
    }
    });

Another option is to remove the event listener each time the window is resized larger than 873 pixels.

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

The local webpage varies from the online version

After uploading my website to my hosting space, I noticed that the online version looks different from the local version. In my local version, I am debugging with Dreamweaver and checking responsive behavior with Google DevTools. Everything seems fine - ...

Sending an Ajax POST request from a Node.js server

I am running a Node.js server with Socket.IO that communicates with a Python server using Django. I am looking to make a POST request from the Node.js server to the Django server on a specific method without utilizing any jQuery functions due to their depe ...

Building an accordion collapse feature in HTML using CSS and JavaScript

I've been working on creating an accordion interface, but I'm facing an issue where only the first collapsible button works properly. The rest of the buttons are not functioning and don't even appear on the page. When I remove the CSS styli ...

Incorporate CSS styling within a PHP document

Many individuals are aware that HTML can be embedded within a PHP file. However, can CSS also be included in a PHP file and accessed using <link rel="stylesheet" type="text/css" href="mystyle.php" /> to make it act as a CSS file? While it is possib ...

Dynamic sliding effect in CSS for seamless showing and hiding of div elements

I stumbled upon a fantastic solution in these forums How to create sliding DIV on click? However, what I really wanted was for the content to fade in and out with just a click of a button. Here is the code snippet I am currently working with: <html> ...

jquery line break in textarea

There is a 'edit description' button that, when clicked, makes text disappear and reappear if (id == 'commedit') jQuery(this).html('<textarea>'+jQuery(this).text()+'</textarea>'); else i ...

Is the OnClientUploadStart function failing to work correctly with the "UploadStart" attribute?

Hey everyone, I'm currently working on an Ajax file upload feature and everything seems to be in order except for the function which is not working properly. OnClientUploadStart="UploadStart" I'm unsure of what mistake I might have made here. C ...

The issue with the table inside a bootstrap modal is that it is not properly sized and does

I am facing an issue with a modal that has two columns. One of the columns contains a table which is too wide and requires horizontal scrolling. I need help to make the table fit into the column without any scrolling problems. The table should be able to s ...

Using JavaScript to modify a JSON document

Currently, I have a .json file with the following format: [ [ 1513814400000, 0.8433 ] ] Here's my query: I want to update every second value in this file. For example: 0.8433 -> 8.433 I've already created a JavaScri ...

Change the selection so that only the initial one appears in gray

Is there a way to make the text inside a select field gray out when the first option is selected? Can this be accomplished with just CSS or does it require JS? I have attempted altering the style of the first option, but it only affects the text color in ...

Leverage Bootstrap 4 for achieving flexible layouts and centering content with two elements using flex and justify-content

By using the d-flex, justify-content-center, and flex-grow-1 classes, I was able to achieve my desired layout with just 3 divs. <div class="row bg-primary d-flex justify-content-center"> <div class="col-auto"> LEFT </div> < ...

Div's HTML Classes are not triggering the Click Event

I'm attempting to create a custom function that will display notifications in the top right corner of my website, similar to how OS X notifications appear. Instead of relying on an external library, I am using jQuery as a resource. To house my notifi ...

Issues surrounding the break function in PHP and Jquery

Here is a simplified version of PHP and jQuery code for a page that I am working on. The example includes PHP break functions and the file is named test.php. The issue I am encountering is that when trying to load the first part of the page (case 1), the ...

Processing ajax requests in Rails 4 using HTML format

I'm currently in the process of setting up ajax functionality for my contact form and I am currently testing to ensure that the ajax call is being made. When checking my console, I noticed that it is still being processed as HTML and I cannot seem to ...

Calculate the total sum of input values using jQuery

Here is the HTML I've been working with: I am trying to create a script where one textbox will display the total amount, and another textbox will display the following data: "name": [{ "id": 3, "qty": 2 }, { "id": 4, "qty": 5 }] Here's ...

How can you align square cells within a container using CSS grids while maintaining a consistent grid gap?

Our objective is to perfectly align square cells with the edges of their container while maintaining a consistent gap between cells in each row and column. Although this Codepen solution is close, there are two key issues: (1) vertical spacing doesn' ...

What impact does the order of the element I'm specifying in my .css file have on its appearance after being rendered?

(An update has been added below) In my project, I am working with a .css file and an index.html document. The goal is to create a panel of buttons on the screen [to prototype the usability of a touchscreen interface], with each button assigned a specific ...

Bootstrap 4 Multilevel Navbar with Bootswatch design positioned on the right side

How can I modify a multilevel Navbar in Bootswatch 4 (Bootstrap 4) to make the Submenus pop open to the left side? The "dropdown-menu-right" class doesn't achieve the desired result. Can someone provide guidance on how the CSS / Javascript should be a ...

Choose-option "No entries found for that specific query"

Looking for help with setting up a voting function. The vote.js script seems to be working fine, but I'm unable to get the object. Any suggestions? It appears that the POST request is not being sent. Thank you. Encountering this error: Page not foun ...

Designing a customizable header/banner for user personalization

Is it possible to create a custom feature header generator that allows users to personalize it with colors, images, and text, then save and add it to their website? Check out the feature banner demo I created to get an idea of what I'm aiming for. (T ...