Adjusting window size when page is resized

While browsing through SO, I stumbled upon this interesting piece of code:

var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    x = w.innerWidth || e.clientWidth || g.clientWidth,
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;

function t(){
    test.innerHTML = "x = "+x+"\ny = "+y;
}

window.onload = t;
window.onresize = t;

I found a Fiddle Example related to this code and it got me thinking - is there a way to automatically update the values when resizing the window without having to manually refresh by pressing F5?

Answer №1

When running the t function on resize, make sure to update the x and y values within the function as well. Currently, they are only set on load which is causing the issue. Modify your logic so that they are adjusted dynamically within the function. Here is a suggestion:

var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    x, y;

function t() {
    x = w.innerWidth || e.clientWidth || g.clientWidth;
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;
    test.innerHTML = "x = " + x + "\ny = " + y;
}

window.onload = t;
window.onresize = t;

Updated fiddle link

On another note, if you require the window size for updating the UI under certain conditions, consider using CSS media queries instead of relying solely on JavaScript.

Answer №2

Make sure to execute the function when resizing the window as well,

var onresize = function() {
    x = w.innerWidth || e.clientWidth || g.clientWidth,
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;
    test.innerHTML = "x = "+x+"\ny = "+y;
}
window.addEventListener("resize", onresize);

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

When the value is removed, it does not revert back to the initial filtered choices

After clearing the input, I want to display all the original li's again. The issue is that even though .value = '' clears the input, the filter remains active. I could really use some help with this as it's starting to get on my nerves ...

I am encountering a problem while performing JavaScript validations

In jQuery or using the element's ID, I can validate a textbox. For example: var field = document.getElementById('tbxSearchField').value if (field == "") {alert("please enter text");} The HTML code is as follows: <input class="input" id ...

Collaborative JavaScript repository within the Websphere Liberty platform

Is it possible to utilize a JavaScript library (such as Dojo, JQuery, or other custom developed libraries) as shared libraries within a Websphere Liberty server? For instance, I am interested in storing the .js files in either C:\wlp\usr\sh ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

Tips for preventing Chrome from masking the background image and color on an autofill input

Google Chrome Browser has caused the background-color and background-image effects to be removed from the Username and Password input fields. Before autocomplete https://i.stack.imgur.com/Ww7Hg.png After autocomplete https://i.stack.imgur.com/hbG2C.png ...

What is the best way to utilize jspdf for formatting data, specifically when wanting the first column to be in bold?

How can I customize data formatting using jspdf? Specifically, I would like the first column to be in bold and the second column in normal text. Additionally, I want to align them in the middle of the pdf output with different colors for each column. Belo ...

The ng-if directive seems to be causing issues within an ng-repeat loop when used in conjunction with bind-html

Below is the code I am using to bind html in my webpage: <div bind-html-compile="menuButtonView"></div> This is the code in my controller: dashboardService.getTemplateMetaData(data.templateCategory) .success(function(data) { console.lo ...

Error Alert: UnhandledPromiseRejectionWarning in Async Series Causes Concern

I am currently working on a function in my project that uses the async series method to ensure specific tasks are executed in a certain order. In this case, function1 needs to be completed before function2, which must then be completed before function3. a ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

Showing C# File Content in JavaScript - A Step-by-Step Guide

Is there a way to showcase this File (c#) on a JavaScript site? return File(streams.First(), "application/octet-stream", Path.GetFileName(element.Path)); I am looking for something similar to this: <img id="myImg" src="_____&qu ...

Learn how to implement form validation on a sliding form in just 5 easy steps using jQuery

I am new to programming and I struggle to comprehend complex JavaScript code written by others. Instead of using intricate code that I don't understand, I would like to request help in creating a simplified jQuery script for me to implement. Current ...

The clash of interests between jQuery and Bootstrap

I'm facing a problem with conflicting jQuery and Bootstrap files in my header.php code. Whenever I include the jQuery file before the bootstrap.js file, it causes issues with the tabs on my website where clicking on them does not navigate me to the co ...

managing arrays in JavaScript with multiple tables

**I have successfully written code for calculating the sum of inputs in one table** $('#example122').on('input', '.calculate', function () { calculateTotal(); }); function calculateTotal() { var grandTotal = 0; $ ...

Is it possible for node-java to accept anonymous functions as parameters in Java?

I am looking to pass an anonymous function from JavaScript to Java using node-java (https://github.com/joeferner/node-java). Below is a snippet of the Java code for reference: public class Example { public Example() { } public interface Callb ...

Table Header Stays Put Without Shrinking or Expanding with Window Adjustment

I have a sticky table header that stays at the top when scrolling down on my web page. To achieve this effect, I followed the solution provided on css-tricks.com/persistent-headers/. However, I encountered an issue where the sticky table header does not ...

Guide to setting up npm openlpr in a Node.js environment

After attempting to install the npm node-openalpr package, I encountered an error. What steps can I take to resolve this issue? > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cba5a4afaee6a4bbaea5aaa7bbb98bfae5fae5fa">[e ...

Animation for maximum height with transition from a set value to no maximum height

While experimenting with CSS-transitions, I encountered an unusual issue when adding a transition for max-height from a specific value (e.g. 14px) to none. Surprisingly, there is no animation at all; the hidden elements simply appear and disappear instant ...

Is there a way to use jQuery to hide rows in a data table that contain a specific code, such as "1.1" or "1.2," that includes a

When using ajax, I pass data from two inputs to another page. These values are then used in a query to display the results in a data table on the main page within the success function. Now, I'm looking to implement a condition where any data containi ...

Navigating through Leaflet to reference a .json file

Looking to integrate a .json vector layer into a Leaflet.js map, which can be seen on the GitHub page here, with the source code available here. Here's a condensed version of the file for reference (full version visible on the linked GitHub page). & ...

Enhancing Performance of D3 JS for Visualizing Large XML Data

I am working on visualizing a large XML file, almost 1 GB in size, as a graph of nodes and links using D3 Javascript. I am currently working with mac 10.5.8. I have successfully extracted the content of the file, displaying it as: [Object Element]. The p ...