How can you refresh a webpage with Javascript only one time?

When I use the resize function to reload my page, I only want it to reload once when the page size changes from small (less than or equal to 768px) to big or vice versa. Here is my current code:

$(window).resize(function(){
// if(document.body.clientWidth <= ipadWidth && x = 1){
location.reload()
// }
});

Answer №1

It's uncertain if this is the exact solution you seek, but the code snippet provided will execute only once on window resize. It will trigger when the innerWidth crosses the threshold of 768px, behaving differently for sizes above and below that value.

Note: Reloading the page isn't viable as it resets all values upon refresh.

Should reloading still be desired, storing variables in a database isn't sufficient. Tracking individual user sessions would be necessary, leading to unnecessary complexity.

The recommendation is to avoid force refreshing altogether.

If the need for forced page reload arises from styling concerns based on screen size, opt for media queries instead.

For instance:

@media screen and (max-width: 768px) {
  your CSS here
}

In such cases, the specified CSS rules apply until the window width exceeds 768px, following which default rules take effect again.

let isSmall = false
let isBig = false
$(window).resize(function(){
   if (window.innerWidth >= 768 && !isBig) {
      isBig = true
      //location.reload()
      console.log('Triggered for larger screens')
   }
   if (window.innerWidth < 768 && !isSmall) {
       isSmall = true
       //location.reload()
       console.log('Triggered for smaller screens')
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

EDIT Updated answer with examples demonstrating conditional element display/hide using JavaScript.

Two scenarios are covered - on window resize (resource-intensive) and on initial page load (triggered once).

$(window).resize(function(){
   if (window.innerWidth < 768) {
     $(".choiceSubject_btn").show();    
   }else {
      $(".choiceSubject_btn").hide();   
   }
})
 
 
$( document ).ready(function() {
    if (window.innerWidth < 768) {
    $(".choiceSubject_btn").show();     
   }else {
      $(".choiceSubject_btn").hide();   
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="choiceSubject_btn">my button<h4></h4><i class="fas fa-caret-down"></i></button>

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

Exploring Objects without the need for loops

Currently, I am focusing on optimizing the performance of the following objects: var scheduleFee = { poor = {level1:25,level2:25,level3:25} , good = {level1:15,level2:20,level3:25} , vgood = {level1:10,le ...

Prevent anchor jumping caused by popstate event in Safari

This situation is really testing my patience. When navigating within the same page using anchors, the browser automatically takes you back/forward to the location of that link in your history when popstate is triggered. One might think that you could prev ...

JavaScript array images are not showing when using the img tag

For this module, I am working on creating a flipbook (magazine) using images stored in a JavaScript array. However, I am facing an issue where the images are not loading up properly. Instead of displaying the image, it shows as [object" htmlimageelement]=" ...

Issue with fixed positioning on iPad devices

A unique feature we implemented on our site is a small control that is positioned at the bottom of the screen. However, upon viewing the site on an iPad, the control does not stay fixed at the bottom but rather floats in the middle. What's the issue ...

Can one image impact other images through a wrapping function?

I am facing an issue with positioning 3 images independently from the window size using the position: relative declaration. When I try to define positions for the first 2 images and then insert the third one, it disrupts the position of the first two. Is ...

Converting data from a JSON-like file format into valid JSON using JavaScript

I have a unique situation where I am dealing with numerous files that have an unusual file extension. My goal is to utilize JavaScript to read these files and then convert their contents into either JSON or regular JavaScript objects. Is this task even fe ...

Omitting an element from the CSS styling

How can I create a CSS selector that targets the text content within this snippet, excluding the <label> component? Essentially, I want to style the text in the div while leaving the label unchanged. <div id="edit-cc" class="form-item form-type ...

Troubleshooting a problem with AJAX returning the data

Currently, I have a javascript function that calls another javascript function called zConvertEmplidtoRowid. This second function utilizes an ajax call to execute a query and retrieve data stored in a variable named rowid. My challenge lies in figuring out ...

Enhance the appearance of CardMedia in React Material UI with custom rendering options

I am curious about how I can customize the CardMedia component of React Material UI to achieve a design similar to this: https://i.sstatic.net/Spdbz.png In the desired result, there are 3 elements: The image itself in WebP format (see example) A dur ...

Is there a way to customize jqwidgets jQuery grid cell classes/styles based on row ID and column name?

{ text: 'sell', datafield: 'Sales', width: '3%', columntype: 'button', filterable: false, cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) { return &apos ...

Enhancing the accessibility of Material UI Autocomplete through a Custom ListboxComponent

I have developed a custom ListboxComponent for the MUI Autocomplete component in MUI v4. How can I ensure that it meets the necessary accessibility requirements, such as navigating through options using the arrow keys? <Autocomplete ListboxComponent ...

Transferring information from an HTML table to a PHP page using AJAX

I am currently working with the Laravel framework and have an index page that dynamically retrieves a table from another page using AJAX within a div element. I now need to allow users to edit the table values and send the modified data to a PHP page for ...

How to Accurately Obtain Serial Numbers in Add, Remove, and Clone Operations Using My Calculation Method

How To Properly Calculate SrNo in the Add, Remove, and Clone Functions By clicking "Add" multiple times, deleting rows, and then adding again, the SrNo becomes incorrect. I want it to calculate properly with my custom function... <div id="button_pro" ...

Step-by-step guide on designing a search bar integrated with an image submit button

I have a task to replicate the search bar design of Google Images. This is the current state of my html code: <form id="search"; action="https://www.google.com/images"> <input type="text" name="q ...

Tips on removing properties from an object recursively according to their key/value pairs

My current task involves removing specific children of an object based on whether their "size" key is set to 0. To achieve this, I am utilizing the npm package directory-tree to generate a JavaScript object representation of a chosen directory. The stru ...

value in the text field changing when focused

Is there a JQuery solution for displaying the keyword when text is entered in the value input? Click here to view an image example. ...

Discovering a device's model using JavaScript

How can I use Javascript to redirect users to different download pages based on their device model? ...

What is the process for creating a List Grid View utilizing this particular code?

I attempted to modify the stylesheet extensively and also created a small function in JavaScript, but unfortunately it did not yield the desired results. <div class="row featured portfolio-items"> <div class="item col-lg-5 col-md-12 col-xs ...

What are the steps for releasing a collection of Vue.js components?

Currently, I am working on a project that involves a Vuex module and abstract components that users can extend. My goal is to clean up my codebase by separating this project into a well-tested module and publishing it on NPM. In order to achieve this, I ha ...

Having difficulty breaking down values from an object

Attempting to destructure the data object using Next.js on the client side Upon logging the data object, I receive the following: requestId: '1660672989767.IZxP9g', confidence: {…}, meta: {…}, visitorFound: true, visitorId: 'X9uY7PQTANO ...