Using jQuery to reset variables after the browser has been resized

I am attempting to develop a jQuery function that can be invoked both when the page loads and when the browser window is resized.

jQuery(document).ready(function($) {

function setWidth() {
    var windowWidth = $(window).width();
    var boxWidth = $('#addbox').width();
    var paddingWidth = (windowWidth - boxWidth) / 2;
};

$(setWidth);

$(window).resize(setWidth);

$(".scroll").click(function(event){     
    event.preventDefault();
    $('html,body').animate({scrollLeft:$(this.hash).offset().left-paddingWidth}, 750);
});

});

However, it seems like this code is not functioning properly as Firebug indicates that paddingWidth is undefined. What mistake am I making?

Answer №1

Variables retain the scope in which they were initially defined (using var). In this scenario, it signifies that their scope is limited to setWidth and they are reset with each execution of the method.

To ensure functions in descendant scopes have access to their values, it is recommended to move them into a broader scope.

jQuery(document).ready(function ($) {
    var windowWidth, boxWidth, paddingWidth; // variables declared in this scope

    function setWidth() {
        windowWidth = $(window).width(); // variables set within this scope
        boxWidth = $('#addbox').width();
        paddingWidth = (windowWidth - boxWidth) / 2;
    };

    setWidth(); // calling the function

    $(window).resize(setWidth);

    $(".scroll").click(function (event) {
        event.preventDefault();
        $('html,body').animate({
            scrollLeft: $(this.hash).offset().left - paddingWidth
        }, 750);
    });
});

It's worth noting that $(setWidth) may seem unnecessary and inefficient. It essentially means "call setWidth when the document is ready". Since you're already within a jQuery(document).ready handler, simply executing the function with setWidth() suffices.

Answer №2

Give this a try

When the document is ready, use jQuery to center a box when the window is resized:

jQuery(document).ready(function($) {

var paddingWidth = 0;

function setWidth() { 
    var windowWidth = $(window).width(); 
    var boxWidth = $('#addbox').width();
    paddingWidth = (windowWidth - boxWidth) / 2; 
};

$(setWidth);

$(window).resize(setWidth);

$(".scroll").click(function(event){     
    event.preventDefault(); 
    $('html,body').animate({scrollLeft:$(this.hash).offset().left-paddingWidth}, 750); 
});

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

Discover the secret to extracting a unique style from inspect mode and incorporating it into your CSS design

I'm currently working on my angular project and I've imported the ngx-editor. My goal is to reduce the height of the editor, but I'm facing some challenges. After inspecting the element, I was able to adjust the height successfully within th ...

What can be done to address the narrowing of the left div element as the right div's child elements grow in size?

Utilizing the power of flexbox, I have organized the UI into left and right panels. The child elements within the right panel are stacked vertically by utilizing the white-space: nowrap; CSS property. However, there seems to be an issue where increasing t ...

Update the div and table without waiting for a specific time interval when an event happens

Currently, I have a table within a div that includes both editing and deleting functionality for records. After deleting a record, I want the table to be automatically updated with fresh data without having to reload the page. Can someone please provide me ...

Issue with the URL associated with the CSS file

As a PHP beginner, I'm having trouble linking to the CSS file using the provided codes. Can anyone help me troubleshoot what's wrong with my code? The issue seems to be in the following snippet from header.php: <html lang="en"> <head&g ...

Engaging JavaScript Navigation

I am looking to create an interactive JavaScript menu or image map where users can press down, highlight, and hit enter on four different items to reveal hidden messages. However, I struggle with JavaScript and could really use some assistance. I have alr ...

Is there a way for my box to avoid reaching the bottom of the page?

Is there a way to prevent my box from reaching the bottom of the page? I am currently using Bootstrap 4 and have tried the spacing utilities, but they don't seem to be effective. https://i.sstatic.net/YRqb4.png Attached is a picture showing that the ...

Optimizing user experience: Implementing different views/orders for mobile and desktop using Bootstrap

Currently, I am working on creating a dashboard using Bootstrap 4 in combination with Angular 5. However, I have encountered an issue that I can't seem to solve: Imagine having the following layout on a desktop screen. The code snippet below is a sim ...

Use jQuery AJAX to send a query string containing a hyperlink to the server and retrieve the results

I am currently working on a PHP website where I have a product page with an "add to wishlist" link. When a user clicks on this link, the product is sent to the server and the page reloads. However, I would like to achieve this using jQuery ajax in order ...

Styling CSS: Tips for making the left column shrink as the window size decreases

I am attempting to create a standard layout using CSS that includes a header, left column, middle section, and right column. However, I want the layout to change when the window is resized to be something like this: header middle | right footer The min ...

Scrolling horizontally in ng-grid version 2.0.11

In my application, I am utilizing a ng-grid with auto height and width. The challenge arises when dynamically adding columns to the grid. If there are too many columns to display, instead of showing a horizontal scrollbar, the columns shrink in size and ap ...

My element's padding being overlooked by Tailwind CSS

In the process of developing a comment/response mechanism through MPTT, I am utilizing indentation to clearly designate replies and their respective levels. The comment.level attribute is being employed to establish the padding value. Consequently, a comm ...

Content and picture within a <button> element do not align on the same row when using flexbox in Firefox browser

I need assistance in aligning a button with an image and text in the center of the same row. However, in Firefox, the image and text appear on separate lines. How can I resolve this issue? This is my current code snippet: button { display: inline-fle ...

What is the best way to enable drag-and-drop functionality for all child elements with the

I am looking for a way to make all contenteditable child elements draggable using jQuery, without the use of external plugins. I came across this helpful code snippet on How do I make an element draggable in jQuery?. function draggable(e){ window.my_ ...

What is the best way to extract the lowest and highest values from a `rangpicker` when using a price slider?

Can someone provide assistance on retrieving the minimum and maximum value after a mouse-drag operation? Kindly review the code snippet below: <div id="double_number_range" style="margin-top: 13px;"></div> <script type="text/javascrip ...

The September/October 2013 release of the Ajax Control Toolkit is causing conflicts with jQuery

After updating our project to utilize the latest October 2013 release of the Ajax Control Toolkit for the HTML editor extender and Ajax file uploader, we encountered unexpected issues. Our ASP.NET 4.0 project, which previously used C#, jQuery 1.9.0, jQuery ...

What is causing justifyContent: space-between not to function properly?

I want to display Text1Text2Text3Text4Text5Text6Text7 at the top with text alignment using justifyContent: 'space-between'. However, when I tried to do so, all texts ended up at the top. <div style={{display: 'flex-item', flex: 1, ...

Scroll smoothly to anchor using variable speed in jQuery

I have a simple HTML website with a few anchor tags. Upon clicking each anchor, there is a smooth scrolling effect implemented using the following function: $(document).ready(function(){ $('a[href^="#"]').on('click',function (e) { ...

Trouble with HTML CSS rendering compatibility across different browsers

So, I've built this page with a gradient background and three white divs acting as columns. Each column contains some text, and it displays perfectly in Google Chrome. However, the gradient appears taller in Firefox and Internet Explorer, pushing the ...

Text wrapping to the right of an image in Bootstrap columns

I'm struggling with getting a large block of text to display correctly on the right side of an image. The text keeps dropping below the image when it reaches a certain size or if no width is specified. Adding a fixed width to the text column seems to ...

Only one successful call to Jquery is made, and subsequent attempts will yield the same result

There seems to be an issue with my code that is supposed to change the content in a div when clicking "More News articles," but the change only happens once. I noticed in Chrome Developer mode that a request is fired on every click. Where could the problem ...