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>