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

Sending Parsed Information to Callback for Flexible Use

Is there a way to pass the value of coins, or even better, currency to my callback function so I can freely use the parsed JSON data in other functions? function fetchJSON(path, callback) { var jsonReq = new XMLHttpRequest(); jsonReq.onreadystatechang ...

Testing a service resolution in a controller through unit testing

As I attempt to create a test for my home module, I keep encountering an error that reads "unknown provider: service." Interestingly, when I modify resolveSomething in my home module to output a string, the app functions as expected, indicating that the re ...

Connecting Formik with the react-phone-number-input library: A step-by-step guide

I am currently working on developing a form using Formik, Material UI, and the React-phone-number-input library for phone number formatting. I have encountered an issue where the formatted phone number is not being inserted into the Formik state, causing F ...

Tips for Automatically Loading Dependencies in AngularJS

Currently, I am working on an Angular application where I am designing various widgets using HTML5. Here is a snippet of the code structure: <html ng-app> <div ng-controller="widget1"> </div> <div ng-controller="widget2"> ...

React components do not re-render when the context value changes

The issue with React not re-rendering when the context value changes persists I am using tailwindcss, React(v18.2.0), and vite(3.2.4). I have already attempted i want that clicking on TodoItem should change the completed value in the todo using React con ...

Unable to retrieve the text enclosed between the:: before and after the:: marker

I attempted this using the XPATH finder in Chrome, and it highlighted the element. However, when running my Selenium script, I received the following error: Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: ...

Difficulties encountered when trying to edit data using a combination of Modals and

Hey all, I'm working on a basic application and looking to update my CRUD operations using jQuery/ajax and bootstrap modal forms. I'm new to jQuery and encountering an issue with editing data. When I call the Get action for editing in the control ...

There seems to be an issue with ngOptions in Angular as it is

Calling all angularjs experts for assistance... Currently integrating cake with angular. Utilizing a rest controller to enable communication and retrieve options in a serialized json format as displayed below Attempting to populate dropdown options: &l ...

Is there a way to conceal the parent element when the child element is hidden from view?

Wanting to remove the stars badge in the review section of a Shopify store when there are 0 reviews for the product. The goal is to have the badge appear automatically once a review is received. Here's the code snippet: HTML <div class="spr- ...

Utilizing jQuery to send AJAX requests and display the results on separate lines within a textarea

My form includes a text area where users can enter keywords, one per line. I would like to implement the following functionality: upon clicking a button, an ajax request will be sent to the server to retrieve the result for each keyword entered. The resul ...

Implementing relative path 'fetch' in NextJs App Router

When attempting to retrieve data using fetch("/api/status"), the URL is only detected when utilizing the absolute path: fetch("http://localhost:3000/api/status"). This is happening without storing the path in a variable. ...

Creating seamless transitions between pages using hyperlinks

On the homepage, there are cards that list various policies with a "details" button above them. Clicking on this button should take me to the specific details page for that policy. However, each product can only have one type assigned to it. For instance: ...

Applying CSS dynamically to a mat-cell in Angular 6

In my material table, I need to apply specific CSS classes based on the content of the cell. These are the CSS classes that I am using .status-code{ flex: 0 0 10% !important; width: 10% !important; } .status-code-success{ flex: 0 0 10% !impo ...

Troubleshooting Knockout.JS: Why self.myObservable is not working and the importance of code organization

My webpage uses knockout to handle a search field, dropdown selection, and page number. These elements are all initialized with default values for the first run or when the page is accessed. I'm encountering an error that says: "self.selectedTeamId i ...

Determining the Last Modified Date for a Sitemap using Javascript

I am trying to replicate the date format shown within <lastmod></lastmod> tags in a sitemap.xml file. How can I do this? The desired output is as follows: <lastmod>2016-01-21EEST18:01:18+03:00</lastmod> It appears that 'EEST ...

The touch event doesn't seem to be functioning properly on the div element, but it works perfectly on the window element

I have a dilemma that's been puzzling me lately. I'm trying to append a touchevent to a div, but my current method doesn't seem to be working. Here's what I've tried: $("#superContainer").bind('touchstart', function(even ...

Is there a way to prevent an ajax call from refreshing the page?

I've implemented image upload functionality in my project. However, when I click the upload button and select a file, the images are displayed via an AJAX call with HTML code. Unfortunately, afterwards, the page refreshes and all form data is lost. E ...

Overlapping Dropdown Javascript Menus

To achieve the desired effect in the header, I need to create two expandable dropdown menus for the first two titles. My coding experience is limited, especially when it comes to javascript and jquery. Currently, I have managed to create the effect for one ...

Retrieve the function-level variable within the while loop's else statement

Struggling with node.js, I find myself facing the challenge of accessing a variable declared at the start of a function from an else statement nested within a do while loop: function myFunction(){ var limit = 2000; var count; var total; va ...

Slideshow plugin glitch on Safari and Opera caused by jQuery implementation

My current project involves utilizing a fantastic plugin called Sequence.js for creating animations and transitions with CSS3 based on jQuery. I have set up a simple responsive fadeIn-fadeOut slideshow using this plugin. While everything works smoothly an ...