JQuery triggers multiple function calls when the window is resized

My current project involves the following tasks:

- When the window's width is less than 700px and a user clicks on the gray bar at the bottom, a red menu should slide up and remain visible.

- If the window's width exceeds 700px, clicking on the gray bar should have no effect.

To ensure these functionalities work seamlessly even when the window is resized after the page has loaded, I have attached a resize() event listener to the browser window.

If you want to test the behavior yourself, here is the link to my Codepen: http://codepen.io/Chiz/pen/xwrpWG (Please read the instructions below before clicking!)

To replicate a strange issue:

1) Resize your window to less than 700px, then click on the provided Codepen link above (if unsure about the dimensions, simply make it very small).

2) Click on the gray bar at the bottom. You should see a red rectangle sliding up and stopping. Click again to see it slide back down. Repeating this action should cause the red rectangle to slide up and down each time, which is the expected behavior.

3) Now, resize the browser window without reloading the Codepen page. You can make the window wider or narrower - it doesn't matter as long as there is a change in the window size. Click the gray bar again. A bug will appear where the red rectangle slides up and down multiple times!

Sometimes, the number of slides matches the number of resizes! :-O

How can I resolve this issue?

//bind click event to the gray bar on page's first load
showMenuIfWidthSmallerThanSevenHundred();

//detect window resizes
$(window).resize(function() {
  showMenuIfWidthSmallerThanSevenHundred();
});


function showMenuIfWidthSmallerThanSevenHundred() {
  if ($(window).innerWidth() <= 700) {
    $("div").on("click", function() {
      /* make menu fill the entire screen that is
      not occupied by the gray bar */
      var nMenuHeight = $(window).height() - $(this).height();

      $(".menu").height(nMenuHeight);

      /* position the menu so that the bottom of the menu
      touches the top of the gray bar */
      $(".menu").css("bottom", $(this).height());

      //make menu slide upwards / downwards
      $(".menu").slideToggle();
    });
  }
}
div {
  width: 100%;
  height: 53px;
  background-color: gray;
  position: absolute;
  bottom: 0;
}
.menu {
  width: 100%;
  height: 100px;
  background-color: #F08080;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div></div>

<div class="menu"></div>

Answer №1

To optimize your event handling and prevent it from firing too frequently, consider implementing a debounce function. One highly recommended option is Paul Irish's smartresizer, which effectively utilizes debouncing for this purpose.

For more information on Paul Irish's smartresizer, you can visit the link below:

As explained in the tutorial, you can easily integrate this functionality using a simple listener like the one shown below:

 $(window).smartresize(function(){
    // write your code here...
 });

This technique is especially useful for optimizing events such as resize, scroll, and many others.

Answer №2

Upon careful consideration of the hints and feedback provided in this discussion, I believe that I have successfully managed to solve the following issue:

http://codepen.io/Chiz/pen/rOwPEm

In summary, when the window width is less than 700px and the gray bar is clicked, a red rectangle slides up. Subsequent clicks on the gray bar will slide the red rectangle back down.

If the window width exceeds 700px, clicking the gray bar will not trigger the sliding action of the red rectangle. Additionally, if the red rectangle is already visible and the user resizes the browser window to be wider than 700px, the red rectangle will slide back down automatically due to the increased width.

I must express my admiration for Underscore.js! Cheers!

$(window).resize(_.debounce(function() {
  showMenuIfWidthSmallerThan7Hundred();
}, 500));

function showMenuIfWidthSmallerThan7Hundred() {
  if ($(window).innerWidth() <= 700) {
    $("div").off("click.mynamespace").on("click.mynamespace", function() {
      /* make menu fill the entire screen that is
      not occupied by the gray bar */
      var nMenuHeight = $(window).height() - $(this).height();

      $(".menu").height(nMenuHeight);

      /* position the menu so that the bottom of the menu
      touches the top of the gray bar */
      $(".menu").css("bottom", $(this).height());

      //make menu slide upwards / downwards
      $(".menu").slideToggle();
    });
  }
  //if window is wider than 700px, unbind the click event and slide   the menu back down
  else {
    //check if menu is shown. if yes, make it disappear
    if ($(".menu").css("display") != "none") {
      $(".menu").slideToggle();
    }

    $("div").off("click.mynamespace");
  }
}
div {
  width: 100%;
  height: 53px;
  background-color: gray;
  position: absolute;
  bottom: 0;
}
.menu {
  width: 100%;
  height: 100px;
  background-color: #F08080;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<div></div>

<div class="menu"></div>

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

Tooltip displacement on the webpage

I'm encountering an issue with the placement of tooltips in my buttons. The problem is specifically with the last, right-most button tooltip - it seems to be displaying on the left side of the page instead of below the button as intended. Check out t ...

Java Applet for capturing specific sections of a webpage to create a screenshot

Does anyone know of a way (applet or something else) to capture a screenshot of the content within a specific div on a webpage? I came across this Java code for capturing a screenshot of the entire screen: import java.awt.AWTException; import java.awt.Re ...

Tips for preventing abusive input using jQuery

I'm currently diving into jQuery and looking to create a form that disables the submit button and clears the input if any abusive words are detected. I would appreciate some assistance with this task. Below is the code snippet I have been working on. ...

In React development, a div (button) is visible, but in the production build, it becomes hidden from

I have been working on a website for my job, and I have added a "Gallery" button on top of two slideshows. Everything works perfectly fine on the development build, but when it comes to the production build, the button doesn't show up for some reason. ...

Creating a button in ReactJS with text displayed under an icon

Presently, I am working with a component that looks like this: https://i.stack.imgur.com/qGCwj.png This is the code for the component: import React from "react"; import {withStyles} from "material-ui/styles"; import Settings from "material-ui-icons/Setti ...

Trouble Ensues as CSS Tables Misalign with Bootstrap Framework

After meticulously slicing up multiple images in Photoshop and exporting them with the necessary CSS table mark-up, everything appeared to be perfectly aligned. However, once the Bootstrap CSS file was included on the page, some of the images started going ...

Retrieve data from AJAX once the cycle is complete

Currently, I am attempting to calculate the sum of results from an external API by making a single request for each keyword I possess. The code is functioning properly; however, the function returns the value before all the ajax requests are completed. Eve ...

When using a jQuery AJAX call, the special character % is sent to the server side as &#37;. This was successfully updated

I am working with a Java program that generates an HTML form populated with text from a database. The user can edit the text in the form, and upon submission, it is sent back to the Java backend using a jQuery AJAX call. The modified text is then saved in ...

The failure of numerous asynchronous calls in the JavaScript Facebook API is causing issues

Utilizing Facebook's Javascript API in my jquery mobile website to fetch albums and photos from a Facebook public page and display them on my website has been quite seamless. The API provides clear instructions on how to accomplish this, and I was ab ...

Using radio buttons to toggle the visibility of a div element within a WordPress website

I am currently working on creating a WordPress page using the custom page tool in the admin interface. My goal is to have 3 radio buttons, with 2 visible and 1 hidden. The hidden button should be automatically checked to display the correct div (although ...

Struggling to make JQuery AJAX POST function properly on my WampServer localhost

My current project involves developing a WordPress website locally using WampServer. In the process, I have created a custom js file named custom-js.js, which is located at C:\wamp64\www\wordpress\wp-content\themes\my-theme&bs ...

What is the Best Way to Utilize CSS ID Selectors with Next JS?

After discovering that npx create-react-app is no longer supported, I decided to delve into Next JS as a new framework. My goal now is to transition one of my websites from pure HTML, SASS (CSS), and JavaScript to utilizing Next JS and SASS. The current c ...

Tips for successfully passing an object with a list property in an ajax request

I have encountered a similar problem to This previous question, but I am struggling to implement the solutions provided. I am unsure of where to include the ModelBinder code mentioned in the responses, so I will explain my issue here. I am working with a s ...

Turning jQuery Mobile XML into a Table

Recently, I switched from using the jQuery Mobile framework's grid layout to a table layout. However, I encountered an issue where only the first line of data from my XML parse was being displayed. There are actually 8 pieces of data that should be sh ...

IE and Chrome are experiencing issues where the radio buttons are disappearing

Here is the style sheet code: select,input ,td a {border:1px solid green; width:25%;height:25px;font-size:20px;margin- left:.1em;} input.myradio {border:none;width:0%;height:0%;font-size:0%;} And here is the corresponding HTML code: <td><inpu ...

Concentrate and essential

I am encountering an issue with required inputs and the :focus styling on those inputs. When I try to submit empty values, the red border from the required styling appears and does not disappear when I click on the input. As a result, I end up with a stran ...

Pick a selection from a different input

Consider the following two rows: <tr> <td class="contenu"><input type="text" name="numart" id="numart"/></td> <td class="contenu"><input type="text" name="descart" id="descart"/></td> <td class="contenu"& ...

Searching for old values in an array using jQuery and adding new values to the array

I'm attempting to add an object to an array, and if the user changes a select option, the object is added again but replaces the previous object with the same product_id. Any assistance would be greatly appreciated. Thank you. function checkVariatio ...

Styling HTML elements with CSS to create a full width underline effect

Is there a way to make the underlines/borders full width for each line in a paragraph without adding line breaks? I'm seeking suggestions on how to achieve this. Two potential solutions I've considered are using the tag or creating an image, ...

Is there a way for me to scroll and bring the block up to the header when the button is clicked?

My goal is to create a functionality where clicking on the button with the class .booking__button will smoothly scroll the block up under the header. The position of the block should remain consistent, only the scrolling effect should be visible to the use ...