How to prevent jQuery from continually recalculating width on window resize?

Here is the code I've been working on:

http://jsfiddle.net/7cXZj/

    var callback = function () {

  $('.progress-bar').width($('.progress-bar').parent().width() - 190);


  $(".mainpart-background").animate({ width: "80%" }, 800 , function(){
    var sidepartposition = $(".progress-bar").width() * 0.1 + $(".sidepart-content").width() * 0.5 ;
   $(".sidepart").animate({ "margin-right": - sidepartposition }, 100); 
   });

};
$(document).ready(callback);
$(window).resize(callback);


var sidepartpositionResize = $(".progress-bar").width() * 0.1 + $(".sidepart-content").width() * 0.5 ;

$(window).resize(function(){

   $(".sidepart").css( "margin-right", "sidepartpositionResize" );

});

There seems to be a problem with the code:

The span displaying "20%" vanishes when the window is resized. Investigating it using Firebug reveals that jQuery continues to calculate the 80%, showing values like 80.00213, 79.1241, 79.12523, etc. It takes 1-4 seconds for this process to stop and for the span to finally show the correct value of 20%.

It's important to note that this code is meant to work on responsive websites.

As a newcomer to JavaScript, any help or guidance would be greatly appreciated!

Answer №1

Take a look at this code snippet: http://jsfiddle.net/7cXZj/5/

The code provided allows for binding to the end of the resize event, ensuring that the function is not executed multiple times during window resizing.

var animate = function(){
console.log('animating');
$(".mainpart-background").css('width', 0);
$(".mainpart-background").animate({
        width: "80%"
    }, 800, function () {
        var sidepartposition = $(".progress-bar").width() * 0.1 + $(".sidepart-content").width() * 0.5;

        $(".sidepart").animate({
            "margin-right": -sidepartposition
        }, 10);
    }
);    
}

window.resizeEvt;

$(document).ready(function(){
animate();

$(window).resize(function()
{
    clearTimeout(window.resizeEvt);
    window.resizeEvt = setTimeout(function()
    {
        animate();
    }, 250);
});
});

I hope this information proves helpful.

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

What are the steps to make a div with no content inside?

Presently, I am dealing with 2 overlapping transparent div's each containing unique buttons and functionalities in the following manner: .item1{ height:10rem; width:10rem; position:absolute; border:0.5rem solid red; background-color:trans ...

Issue with slide animation in carousel on Bootstrap version 4.5.2 not functioning as intended

Recently, I've been diving into learning Bootstrap (v4.5.2) and decided to implement a basic carousel on my website that slides automatically. Following the documentation on Bootstrap's website, I copied the example code for a simple carousel wit ...

Preventing users from accessing the previous page via the browser back button after logging out in an AngularJS application

Currently, I have developed an angularjs web application and facing a challenge. After logout, I am looking to prevent users from navigating back to the previous page using the browser's back button. Ideally, I would like to display a customized messa ...

Modifying the position of an HTML element within its parent tag using document.createElement

As I dive into learning Javascript, I've come across document.createElement. This method allows me to create an HTML tag and insert it into an existing HTML parent element. However, I have a specific question in mind: Is it possible to choose the exac ...

IDs are an effective way to differentiate between classes within a program

I am facing an issue with displaying user info only when hovering over a specific image. The appearance of the hover effect is correct, but I'm struggling to show the info on just the hovered image. Any suggestions on how to achieve this? To see a l ...

There was an issue encountered while parsing the JSON data - "SyntaxError: Unexpected token . was caught."

Encountering an error in Chrome while parsing JSON data. The JSON sample can be found at this link. It is valid JSON and the server is sending the correct Content-Type value (application/json). Uncaught SyntaxError: Unexpected token . Firefox shows a sli ...

What options do I have for sorting through my inventory using the search feature?

Having some trouble setting up isotope filtering on my search bar. I have managed to get the Isotope function working on checkboxes, but for some reason, my search bar isn't functioning as expected. I found a solution online for filtering results bas ...

Ways to transfer a value to another component in React

Currently, I am working on a project where users can add, edit, or delete movies from a list. While the addition and deletion functionalities are working fine, I am facing challenges with the editing feature. In my Movie component, I have included a text i ...

jQuery Popup Button - Maintain the Current Design

I'm currently working with a jQuery dialog and trying to make one of the buttons appear and function as a default button, while still keeping focus on form elements. I managed to achieve this using the code below. However, I encountered an issue where ...

Removing an element from an array within MongoDB

After closely examining my mongodb data structure, it appears like this: [ { "_id": "582bc918e3ff1bf021ae8b66", "boardName": "Test Board", "created_at": 1479264483957, "__v": 0, "person": [ { "name": "Steve", "w ...

Looping through a PHP foreach function, assigning a distinct identifier for the select element using getElementById

My goal is to extract the price value, $option_value['price'], from a dropdown menu as a string rather than using .value, which fetches something different. I am working with select menus generated in a foreach() loop. Each dropdown menu contain ...

What causes Firefox's CPU to spike to 100% when a slideshow begins that adjusts the width and left coordinates of certain divs?

Seeking Advice I'm in need of some help with identifying whether the code I'm working on is causing high CPU usage in Firefox or if it's a bug inherent to the browser itself. The situation is getting frustrating, and I've run out of so ...

Utilizing JSON with ASP.NET WebForms

Is it recommended to use JSON, JQuery & ASP.NET 2.0 webforms together or is it better suited for MVC with ASP.NET 3.5 & 4.0? When incorporating JSON, should I utilize gridviews and repeaters controls for binding JSON data or should I create custom tables f ...

Is it possible to conceal any spans that are in close proximity to the cursor when hovered over?

Currently, I am working on a project that involves multiple spans placed side by side, with each span containing a letter of the text. My aim is to create a functionality where hovering over one of these spans will not only hide that particular span but al ...

Trigger functions by clicking or bind click events by calling a function?

I need help comparing two similar code snippets: myFunc(); function myFunc() { var e = document.getElementByClassName("link"), i = e.length; while (i--) { e[i].addEventListener("click", function() { //do stuff for each ...

Issue with MethodOverride PUT functionality

I am currently utilizing Node.js, Express, and MethodOverride in an attempt to update only one part of my user model using a form. User Model: var userSchema = new mongoose.Schema({ email: { type: String, unique: true, lowercase: true }, password: Str ...

Issue: spawn command UNKNOWN while running npx create-react-app

Encountering an error message in the command prompt while trying to create a React app. Here are some details: Node version: v16.16.0 Npm version: 8.15.1 Operating system: Windows 11 Attempted solutions include running the command in PowerShell, cleari ...

`In AngularJS, the same URL ('/') can display different templates depending on the user's login status.`

What is the most effective way to configure routing and templates in AngularJS to display a distinct front end and login area for visitors, while presenting a dashboard to logged-in users all on the same base URL ('/')? These two pages have comp ...

Modify the CSS class dynamically by clicking a button (using class names stored in an array)

How can I dynamically change a CSS class on button press while using an array of class names? When I hard code the classes in a switch statement, everything works fine. However, when trying to pull class names from an array, it jumps to the end of the swit ...

Use Jquery to select the checkbox inside the td element and mark it as

I've created an HTML table with checkboxes in the td elements, like so: <table id="my_table"> <tr> <td><input type="checkbox" name="td1"></td> <td><input type="checkbox" name="td2"></td> </ ...