Detecting Browser Window Width Dynamically [JavaScript]

I want to create a dynamic variable that updates automatically as the browser window is resized in pixels. I need this variable to change without needing the page to refresh, and I don't want it written in the HTML document as it's used further down in the script.

Here's what I have so far:

window.onload = function() {
  var windowwidth = window.innerWidth;
};

window.onresize = function() {
  var windowwidth = window.innerWidth;
};

console.log(windowwidth);

SOLUTION BELOW

window.onload = function() {
  currentWidth(document.body.clientWidth);
};

window.onresize = function() {
  currentWidth(document.body.clientWidth);
};

function currentWidth(w) {

// Math using w goes here

}

Answer №1

Try out the JS Code below on your website and then adjust the window size. Watch as the variable value changes dynamically based on the window resize event.

var a = Math.random();
console.log (a);
window.onresize = function()
{
    a = Math.random();
    console.log (a);
}

Answer №2

Make sure to execute the function within the callback

window.onload = function() {
  checkWindowWidth(window.innerWidth);
};

window.onresize = function() {
  checkWindowWidth(window.innerWidth);
};

function checkWindowWidth(width) {
  console.log(width)
  console.log(width > 500)
}

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

JavaScript communication between clients and servers

I am looking to develop two scripts, one for the client-side and one for the server-side. I came across a snippet that allows for asynchronous calling of JavaScript: <html> <head> </head> <body> <script> (function() { ...

Using JQuery to enable checkbox if another is selected

I have a single checkbox that reveals a hidden div when checked. Inside this div, there are two additional checkboxes. My goal is to disable the initial checkbox if either of these two checkboxes is checked. Here's the HTML code snippet: <p> ...

How to change the state using an object as an argument in the useState hook within a function

This code uses a function component: export default function Account() { We define a constant with inputs as objects: const [state, setState] = useState({ profile: true, orders: false, returns: false, coupon: false, referrals: false, rewards: ...

Passing events from Vue to child components

Looking for a way to make clicking on the outer pill element have the same effect as clicking on the checkbox itself? Check out this HTML code that renders these little boxes: <div class="token-checkboxes"> <span class="checkbox-span" v-for=" ...

What is the best way to transfer the content from a tinyMCE textarea editor to an inner controller using Symfony3 and Ajax

I have two small rich text editors identified as #homepage and #thankyoupage. My goal is to submit the content of these TinyMCE text areas to a Symfony controller. Below is my front-end implementation: https://i.stack.imgur.com/TE1Ys.jpg Currently, I am ...

Simulate a failed axios get request resulting in an undefined response

I'm having an issue with my Jest test mock for an axios get request, as it's returning undefined as the response. I'm not sure where I might be going wrong? Here is the component with the axios call: import {AgGridReact} from "ag-grid- ...

The value retrieved from redux appears to be varying within the component body compared to its representation in the return

Trying to fetch the most recent history value from the redux store to pass as a payload is presenting a challenge. When submitting a query, the history updates and displays the latest value within the map() function in return(), but when checking at // CON ...

Can I exclusively utilize named exports in a NextJS project?

Heads up: This is not a repeat of the issue raised on The default export is not a React Component in page: "/" NextJS I'm specifically seeking help with named exports! I am aware that I could switch to using default exports. In my NextJS ap ...

Tips on how to update the styling of an active link

http://jsfiddle.net/G8djC/2/ Looking to create a tabbed area where content changes based on the tab clicked. The Javascript function switches the link class to active upon clicking. However, struggling to change the color of the active tab beyond the firs ...

Using jQuery functions on inputs within a Bootstrap Modal

I've encountered an issue with my jQuery functions that validate input fields based on a regex pattern. Everything works smoothly when the form is displayed on a regular page, but as soon as I try to implement it within a Bootstrap Modal, the validati ...

Guide on comparing an object against an array and retrieving a specific output

If I were to create a data structure like this: const carObj = {"1234":"Corvette","4321":"Subaru","8891":"Volvo"}; And also have an array that contains the IDs: const myArray = [1234, 4321, 8891, ...

Checking the conditional styling implemented with Material UI makeStyles: a step-by-step guide

For the past few weeks, I've been working on a React app where I heavily rely on Material UI components. One particular component changes its style based on the values of its props. To achieve this, I used the following approach: const useStyles = ...

Is there a way to verify the results of a Python script within a PHP webpage?

For my school project, I am creating a PHP website where I want to implement a Python code Quiz. I envision a scenario where users can input Python code in an on-page editor/IDE and the output is checked automatically using PHP If-function to determine cor ...

Search for a DIV element within iMacro on a consistent basis

I recently started using iMacro and encountered an issue while recording a script that involved clicking on a pop-up when it appeared on the screen. The problem arose because the pop-up only appears when a new event is posted. Therefore, when I initially c ...

Creating a unique input box using CSS and HTML

Could someone help me achieve an input box like the one shown in the image below? https://i.stack.imgur.com/XtVNj.png Since I am new to CSS, I am not sure how to put text inside the border of an input box. Should I style the input directly or create a di ...

Transferring the link value to an AJAX function when the onclick event is triggered

I have a link containing some data. For example: <li><a href="" onclick="getcategory(this);"><?php echo $result22['category']; ?></a></li> I need this link to pass the value of $result22['category']; to ...

Merge the outputs of all While loops into one variable

Take a look at my custom script: $sql = "SELECT * FROM notifications"; if($result = mysqli_query($link, $sql)) { if(mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_array($result)) { $notification .= " <a class=&apo ...

Creating dynamic scroll animations for sidebar navigation in a single-page website with anchor links

I need help creating a seamless transition between anchor points on a single page, while keeping a fixed navigation menu that highlights the active section. As a novice, I am unsure how to incorporate "( document.body ).animate" or any other necessary code ...

Creating subpages using IDs can be accomplished by following these simple steps

Currently, I am in the process of developing a website that contains a plethora of information, specifically news articles. Each news article on my site features an introduction and a header. Upon clicking on a particular news article, the full content is ...

Redirecting in AngularJS after a successful login操作

Is there a way to redirect users back to the original page after they login? For example, if a user is on a post like www.example.com/post/435 and needs to log in to "like/comment" on the post, how can I automatically redirect them back to that specific po ...