Is there a way to refresh CSS styles when the window width is adjusted?

Is there a way to refresh CSS styles when the window width changes?

I attempted this method, but unfortunately it did not work as expected. A simple refresh (F5) helps to rectify the CSS tags.

jQuery(function($){
    var windowWidth = $(window).width();
    var trigger = 1024;
    if (windowWidth < trigger) var smaller = true;
    else var bigger = true;

    $(window).resize(function() {
        if(windowWidth != $(window).width() &&
            ( ( smaller == true && $(window).width() > trigger ) ||
              ( bigger == true && $(window).width() < trigger )
            )
          ){
            window.location.reload(); 
            return;
        }
    });
});

Sample CSS Code

.example {
    display: block;
    padding: 12px;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 10;
}

@media screen and (min-width: 1024px) {

    .example {
        left: 80px;
        top: 80px;
        width: auto;
        padding: 8px;
    }

}

The original CSS styles were altered by some JavaScript, hence I aim to reload the original ones when the window size shifts from either being smaller or larger than 1024px.

Answer №1

To achieve your desired functionality (which isn't very clear to me), you can integrate your code within a jQuery resize event.

Consider the following example:

$( window ).resize(function() {
  $( "body" ).prepend( "<div>" + $( window ).width() + "</div>" );
});

In general, it may be more efficient to utilize CSS media queries rather than using JavaScript or jQuery to alter CSS based on viewport width changes.

Answer №2

It actually functions correctly if the function is invoked with a delay

setTimeout(function(){
    window.location.reload();
},1); 

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

Transferring data from jQuery Ajax to PHP

I'm facing a challenge in retrieving a value back to PHP that I can manipulate and save to the database. It appears that using the GET method with jQuery AJAX is not yielding the desired results. Below is the PHP code snippet where I attempt to captur ...

modern marquee

I have implemented a marquee tag that displays news from my database. In order to keep the marquee up-to-date without refreshing the entire page, I utilized ajax (update_panel + timer). However, I am encountering an issue where the marquee does not continu ...

The input form in my Node.js project is not adapting to different screen sizes. I am currently utilizing ejs as the template

I have integrated ejs as a template in my Node.js project, but I am encountering an issue with the input form in the following code snippet. The form is unresponsive, preventing me from entering text or clicking on any buttons. What could be causing this ...

Error: Trying to assign a value to a null property

I am facing an issue while trying to dynamically create "iframe's textarea" and insert the value of a variable. Unfortunately, I keep encountering an error. Any suggestions on how to resolve this problem? P.S: Using Google Chrome as the browser ...

Using the Ruby on Rails link_to tag along with a mouseenter jQuery function allows for dynamic

How can I make an image display in a div when the mouse hovers over a link_to using Rails? The code below seems to work, but I'm unsure of how it functions. <a href="#" class="nav-link roll"> <%= image_tag("chair1.jpg") %>Chesterfield Cha ...

It appears that the JavaScript array is able to modify itself autonomously

Currently, I am working on a project using P5.js where I am saving values in an array and then creating a copy of that array to manipulate. However, I have encountered an issue where manipulating the second array also changes the original one, and I cannot ...

How can I notify an error in CoffeeScript/JavaScript when a parameter is not provided?

Initially, I believed that my code was clever for accomplishing this task: someFunction = (arg1, arg2, arg3) -> if _.some(arguments, (a) -> a is undefined) throw new Error "undefined parameter" My goal was to throw an error if any of the para ...

Ensure HTML5 video fills window completely without any overflow

I'm currently developing a new open-source alternative to Plex and I am facing some challenges with the in-browser video player. My goal is to have the video player maximize its size within the window during playback, similar to what Chrome and Netfli ...

Combining two objects in AngularJS to create a new merged object

Is there a way to merge object1 and object2 into object3, updating values corresponding to matching keys while ignoring unmatching keys? var object1 = { "pii" : "val1", "loc" : "val2" } var object2 = { "rrb" : "val3", "voc" : "val4" } var obje ...

I aim to continuously refresh a dynamic canvas line chart with JSON data

Having trouble with my code - the chart isn't updating. I'm new to using canvasJS charts and could use some help. <%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%> <%@ page import=”java ...

Why am I experiencing a problem with my ajax call only working once when I submit forms that are rendered with @Html.Render

I have a scenario where my index page loads with two partial views, each containing an ajax call that filters content based on date. The issue I'm facing is that the ajax call only works once successfully, and subsequent attempts cause a full page ref ...

Receiving a console notification about a source map error

Recently, I started receiving this warning in my console: "Source map error: request failed with status 404" resource URL: map resource URL: shvl.es.js.map" Has anyone encountered this issue before? I'm unsure of what it might be? This is my webpa ...

Using Jquery to create a slideshow with a div that is set to absolute

<!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ $("#flip").click(function(){ $("#panel").slideDown("slow"); }); }); ...

Unable to hear sound on Mozilla Firefox

I am facing an issue with playing an audio file using the audio tag inside the body element. The audio plays perfectly in Chrome once the body has finished loading, but it fails to play in Mozilla Firefox. I even attempted to download the audio file and pl ...

How to Set a Background Image for a Div in React?

render(){ const { classes } = this.props; const { imageDescription } = this.props.imgDesc; const { currentIndex } = this.state; var fullPath = `../images/Large/${(imageDescription[currentIndex]).imagePath}.jpg`; con ...

Pulling a div from beneath numerous other divs

I have been attempting to create a test case for a web application we are developing and I am on the verge of finding a solution, but there is one final hurdle that has me puzzled... Our requirement is to enable div elements to be draggable (which is work ...

`Resizing Images with Cropping Functionality`

I am looking to develop a feature that enables users to resize images after uploading them. The image should be placed within a crop frame, allowing users to drag, move, and resize it as needed. Here is a visual concept of what I have in mind. If anyone c ...

Sending dynamic data from PHP to jQuery flot pie chart

In my PHP code, I have defined 3 variables. $record = "283-161-151"; $rec = explode("-", $record); $win = $rec[0]; $draw = $rec[1]; $loss = $rec[2]; The variables $win, $draw, and $loss are displaying correctly, indicating they are working as intended. ...

Is there a way to incorporate the MUI theme color into inline styles?

Imagine I have the following tabs displayed below. Is there a way to implement MUI's primary and secondary colors for inline CSS? My goal is to personalize the colors using my own palette. <Tabs value={value} ...

When using JSON.Stringify in a React App, it only displays the first item and the length of the object instead of all the other items

Working on a React App, I encountered an issue while trying to convert an array to JSON and send it to the server. My approach was like this: console.log(JSON.stringify(mainArray)) I anticipated seeing output like this during testing: "breakfast": { ...