attempting to access a variable which was initialized within a function in different sections of the code base

My goal is to retrieve a variable created within a function that is nested in a resize event parameter in jQuery. This variable should be dynamically updated each time the user resizes the browser window. I intend to utilize this variable to set the width of a div element with the class '.slide'. Essentially, whenever the user resizes the browser, I want the .slide element to adjust its width accordingly.

$(window).resize(function(){
        var windowWidth = $(window).outerWidth();
        return windowWidth;
    }) 

I plan to use the windowWidth variable

// To set the width of each slide equal to the window width
var slideWidth = $('.slide').css("width", windowWidth)

Here I will use slideWidth

$('.slide').css('width', slideWidth);

I may need to utilize the windowWidth variable in other parts of my code

While attempting to create a slideshow that spans the entire width of the page, I encountered issues when setting the width to 100%. Images within the slideshow would not align correctly using the float left property.

Link to problematic fiddle

Thank you for the suggestions provided thus far. However, most responses only address how to handle the resizing aspect but do not cover how the width variable can be integrated into other sections of the code. The moveSlide() function seems to be neglected in many answers, which limits reusability.

Answer №1

If you're searching for it, there's no need to set slideWidth as a global variable. Instead, utilize $(window).width() to determine the current window width when resizing. See a functional example on this link.

Answer №2

It's essential to establish the variable windowwidth on a global scale

var windowwidth=$(window).outerWidth();
$(window).resize(function(){
    windowwidth = $(window).outerWidth();
    //return windowwidth;
    demo();
});
function demo()
{
    var slideWidth = $('.slide').css("width", windowwidth)
    slides.wrapAll('<div id = "slideHolder"></div>')
    slides.css({"float" : "left"});
    // var bodywidth = $('body').outerWidth();
    // var windowwidth = $(window).outerWidth()
    $('.slide').css('width', slideWidth);
    $("#slideHolder").css("width", slideWidth * numberOfSlides );
}
demo();

Take a look at this working fiddle for reference

Answer №3

$(window).resize(function(){
    let currentWindowWidth = $(window).outerWidth();
    return currentWindowWidth;
}) 

In this scenario, the window width will be confined to the function's scope and then returned as a value.

It is not being set in the global scope for access from other places.

If you want to make it accessible globally, you can do:

window.windowWidth =  $(window).outerWidth();

This way, you can access it from the global scope.

Answer №4

To achieve that, simply create a global variable instead of declaring it as a local variable within the function!

Alternatively, you can utilize localStorage to store the specific width as shown below:

$.localStorage( 'example', {info:'value'} );

$.localStorage( 'example' );

Answer №5

functional Fiddle example.

$(document).ready(function(){
  let screenWidth = $(window).outerWidth();

In order to ensure the variable screenWidth is accessible globally, it needs to be declared within the $(document).ready function with the current window width. Remember to remove the let before screenWidth in the $(window).resize function to avoid using a local variable that cannot be accessed outside of the function.

Answer №6

By defining the variable windowWidth within a function, you are limiting its accessibility to only that function's scope. To make it available globally, make sure to declare windowWidth outside of any functions.

A similar adjustment was needed for the variable slideWidth in order to make your demonstration function properly. You can view the revised code in action by visiting:

JSFiddle Demo

Answer №7

To ensure your variable is accessible globally, declare it in a global scope

var windowWidth = 0;

$(window).resize(function(){
        windowWidth = $(window).outerWidth();
        return windowWidth;
    }) 

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

Storing notes using HTML5 local storage

I recently developed a unique note-taking web application where users can create multiple notes and switch between them using tabs on the left side. My next step was to implement local storage for saving these notes, so I inserted the following code: $(d ...

Error with toUpperCase in Select2 on markMatch operation

Recently, I've been utilizing select2 for non-ajax queries and it has proven to be quite useful. However, I encountered a challenge when attempting to use it for an ajax json response. Despite scattered clues in the extensive document on how to implem ...

Enhancing user experience with Bootstrap's body padding and customizable scrollbars

Recently, I encountered an issue with the footer color in bootstrap. To fix this problem, I created a div and removed the extra padding from the body element. You can view the code snippet here: jsfiddle.net/wctGM/9/ However, when viewing the mobile ver ...

Building a Strong Foundation with Bootstrap's Scaffolding and Mixins

I'm a bit confused by the Bootstrap documentation's explanation of scaffolding and mixins. I tried looking up information on scaffolding in CSS, but couldn't find a clear answer. When it comes to mixins, different websites seem to have varyi ...

Troubleshooting: jQuery click event not functioning correctly with if-else statement

For some reason, I can't seem to figure out how to toggle the color of all list items with a class of "link" between blue and black. I've searched through numerous posts but still can't find a solution. Working Example: http://jsfiddle.net/ ...

Unable to access npm run build on localhost

I have developed a web application using react and node.js, and now I want to test it with a production build. After running npm run build in the app directory, I successfully created a build folder. However, when trying to run the application using local ...

Restore Bootstrap Dropdown values to their initial settings when clicked

I need a button that can reset all filter dropdown values to their default values. The current code I have only changes all values to "Filter" when reset, but I specifically need it to reset to "Car brand" and "Model". Here's my code: // set.... $(" ...

AngularJS: Issue with watching arrays and deep $watch functionality

I'm having trouble using the $watch function in AngularJS with an array of boolean values. I want to display a message when there's a change in the array, but it's not working as expected. Check out this code example where the array values ...

Having difficulty including the Column Name in the Jqgrid footer for sum calculation

I was working on the Jqgrid code and found a way to display the sum correctly in the footer of the grid. var colSum = $("#dataGrid").jqGrid('getCol', 'Amount', false, 'sum'); $("#dataGrid").jqGrid('footerData', &a ...

React Router Link Component Causing Page Malfunction

Recently, I delved into a personal project where I explored React and various packages. As I encountered an issue with the Link component in React Router, I tried to find solutions online without any luck. Let me clarify that I followed all installation st ...

Top method for identifying browser window modifications such as navigating back, altering the URL, refreshing, or closing the window

Currently, I am developing a testing application that requires me to trigger a finsihTheTest() function in specific situations. These situations include: When the user attempts to reload the page. When the user tries to navigate back from the page. If the ...

TypeScript multi-dimensional array type declaration

I currently have an array that looks like this: handlers: string[][] For example, it contains: [["click", "inc"], ["mousedown", "dec"]] Now, I want to restructure it to look like this: [[{ handler: "click" ...

Utilizing Npm modules with a jQuery plugin

As a newcomer to Npm packages (coming from Ruby), I am attempting to load a jQuery plugin that is not available on NPM. My task involves building a Chrome extension. The code snippet below is utilized in the content.js script that is injected into the brow ...

How can I transfer a collection of JSON objects from JavaScript to C#?

Feeling a bit confused here. I have some Javascript code that will generate JSON data like the following: {type:"book" , author: "Lian", Publisher: "ABC"} {type:"Newspaper", author: "Noke"} This is just one example, I actually have more data than thi ...

Verify that the input is zero and then proceed to deactivate the submit button if it is indeed zero in AngularJS

app.controller('HelloController', function($scope) { console.log($scope.input1); console.log($scope.input2); if (($scope.op_option == 4) && ($scope.input2 == 0)) { myForm.$invalid; } }); <form id="calc" method="pos ...

Perform an operation in JQuery after a different operation has been completed

Recently, I came across this JavaScript function that displays a loading image for a few seconds before revealing a hidden div: <script type="text/javascript> $(document).ready(function () { $('#load').html('<img style="display ...

Having issues with the alignment on Bootstrap 4, any suggestions on how to fix it?

I'm struggling with the layout of a web page using Bootstrap 4, and for some reason, I can't figure out why it's not displaying correctly. I've been staring at my code for about 15 minutes now, but I just can't seem to identify the ...

Tips for positioning an image next to a list in HTML:

Having recently entered the world of HTML coding, I am struggling to find a clear and precise solution to my issue. I am aiming to create a webpage that consists of a list of HTML elements. https://i.sstatic.net/jQ1o0.jpg Below is the HTML code I have w ...

Eliminate Tracking Parameters from URL

I rely on UTM parameters to monitor incoming links within Google Analytics. Consider a scenario where my URL appears as follows https://www.example.com/store?utm_source=newsletter&utm_medium=email&utm_campaign=spring_sale I am looking to streaml ...

What is the best way to create a scrollable screen in React Native?

I am currently developing an application using React Native. While scrollView works as expected, enabling scrolling on the screen, I am encountering issues with the GestureRecognizer from "react-native-swipe-gestures." Below is a snippet of my simple app: ...