How to refresh the page between window widths 480px to 768px? - javascript

I am currently using the code:
// Resize when less than 768
$(document).ready(function(){
$(window).on('resize',function(){
if ($(window).width() < 768) {
location.reload(); // refresh page
}
else {
// Width greater than 768px for PC
}
});
});
But this reloads the page constantly when the browser is resized less than 768px. Is it possible to have a code that only reloads the page on resize when the browser is say, between 480px and 768px? Thanks!

Yes, of course:
// Resize when less than 768
$(document).ready(function(){
$(window).on('resize',function(){
if (($(window).width() > 480) && ($(window).width() < 768)) {
location.reload(); // refresh page
}
else {
// Width greater than 768px for PC
// Or width is smaller than 480 for mobile
}
});
});

I was trying to find a solution about this one, when I saw the accepted answer..
Please be carefull with your words mate:
But this reloads the page constantly when the browser is resized less
than 768px.
The keyword constantly is misleading, making others to believe that the problem is the constant refreshing of the page, and not the limitation of the conditional.
Anyway, for those poor fellows who thought the problem is the constant renewing, here is a working fiddle of my humble solution:
$(document).ready(function(){
//Set flag refresh to true
var refresh = true;
//If the window width is between wanted limit set flag to false. This is needed for the resize*.
if (($(window).width() > 480) && ($(window).width() < 768)) {
refresh = false;
}
$(window).resize( function(){
/* When resize hits limits check if flag is true, then refresh.
Flag is set to false from above*, after refresh.
Time is needed for the page to load and set the flag to false.
Otherwise flag is not updated and constant refresh keeps happening while resizing. */
if (($(window).width() > 480) && ($(window).width() < 768) ) {
if (refresh == true) location.reload();
} else {
refresh = true;
}
});
});

You could set a variable when the page first loads (in the ready() handler) that checks the initial size of the window. Then only use the resize event if necessary.
$(document).ready(function(){
var initialSize = $(window).width();
//don't resize on small sizes
if (initialSize < 768) { return; }
//otherwise continue
$(window).on('resize',function(){
if ($(window).width() < 768 && ) {
location.reload(); // refresh page
}
else {
// Width greater than 768px for PC
}
});
});

Related

JavaScript execute page resize and reload event simultaneously

I am trying to execute a window resize and page reload event simultaneously. When the screen size is less than 768 px, I am adding an attribute to an element. I also need that attribute added when the page is reload and a specific size as well, not just when its resized. The code I have below works, except when my screen size hs < 769 px, it takes a few seconds for the attribute to be added which affects how it looks. Any tips on how I can fix this?
window.onload = function(event) {
var element = document.querySelector('.filter-select');
if (window.innerWidth < 768) {
element.classList.add('testing');
element.removeAttribute("size", "4")
element.removeAttribute("multiple", "yes")
} else {
element.classList.remove('testing');
}
}
document.addEventListener("DOMContentLoaded", function(event) {
var element = document.querySelector('.filter-select');
function resize() {
if (window.innerWidth < 768) {
element.classList.add('testing');
element.removeAttribute("size", "4")
element.removeAttribute("multiple", "yes")
} else {
element.classList.remove('testing');
}
}
window.onresize = resize;
});
My only guess is that you doubled up the same process under different events and these events happen at different times thus the NOTICABLE lag.. if this doesn't solve.. this is an amazing question I already upvoted..
function resize() {
var element = document.querySelector('.filter-select')
if (window.innerWidth < 768) {
element.classList.add('testing')
element.removeAttribute("size", "4")
element.removeAttribute("multiple", "yes")
}
else {
element.classList.remove('testing');
}
}
window.onload=resize

jQuery - on resize shows bootstrap modal window for every resolution instead of only specific resolution

When page load if window width >991px fadeIn dropdown form by default, after 4 seconds of delay fadeOut... Question: whether it is recommended to use else statement in this case because practically if if ($(window).width() < 991) .dropdown-menu should not be loaded...
$(document).ready(function () {
if ($(window).width() > 991) {
$(".book.dropdown .dropdown-menu").delay(4000).fadeIn(800).delay(4000).fadeOut(800);
}
});
Second, independently of page load, I want to achieve when is window width > 991px, .book.dropdown should open default dropdown menu which I created, but when is windows width < 991px on click should open JUST bootstrap modal window, but NOT default and modal together.
I want to mention that for the first time after page load, if is windows width > 991px, on click .book.dropdown, dropdown menu opens as expected, when I resize below 991px, on click .book.dropdown, does not open as expected, because opens modal and default dropdown menu (which is defined only for > 991px), when you go back over 991px, modal shows again (problem again).
$(window).on('resize', function() {
var width = $(window).width(); //check window width
if (width > 991) {
$('.book.dropdown, .language.dropdown').on('click', function(e) {
if (!$(e.target).is('.active_language') && !$(e.target).is('.booking.dropdown-toggle')) {
return true;
}
var $el = $(this),
$current = $('.navbar').data('popup'),
visi = function() {
$('.navbar').data('popup', $el.is(':visible') ? $el : null);
};
if ($current != null && !$current.is($el)) {
$('.dropdown-menu', $current).fadeOut(600);
}
$('.dropdown-menu', $el).fadeToggle(600, visi);
});
} else {
$(".book.dropdown").on('click', function(e) {
$('#book-modal-fullscreen').modal('show');
});
};
});
I also tried with this code, but I failed to do
$(window).on('load resize', function() {
var width = $(window).width(); //check window width
...
}).resize();
});
Also I tried
$(document).ready(function() {
if ($(window).width() > 991) {
$(".book.dropdown .dropdown-menu").delay(4000).fadeIn(800).delay(4000).fadeOut(800);
}
function checkWidth() {
var width = $(window).width(); //check window width
if (width < 991) {
$(".book.dropdown").on('click', function() {
$('.modal').modal('show');
});
} else {
$('.modal.in').modal('hide');
}
}
// Execute on load
checkWidth();
// Bind event listener
$(window).resize(checkWidth);

disable click link on touch devices not working as expected

what I'm trying to do
I have dropdown-menus that open on hover and the parent menus have their own landing page link. we're not willing to sacrifice this behavior, but if obviously creates problem for large touch enabled devices. So, I'm detecting touch devices with jquery, and disabling the parent menu click on devices larger than 990px wide. devices below 990px is considered as mobile view and it switches to toggle. This switch between the toggle and the desktop view is expected to continue on screen rotation too.
what is happening
the menu link is disabled on first load and works as expected. Then I rotate the screen (from landscape to portrait) and see the mobile menu as expected and navigate to another page. once the page loads, I rotate it again (from portrait to landscape) and the desktop view is visible, but the parent links are clickable now!
I want to prevent this click event on second rotation too. HTML is standard bootstrap 3 navigation code and my js is like this:
function isTouchDevice() {
return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}
$(document).ready(function () {
$(window).resize(function () {
var o = $(window).innerWidth();
function isTouchDevice() {
return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}
if ((isTouchDevice() === true) && (o >= 990)) {
$('.navbar .dropdown > a ').each(function () {
$(this).on("click", function(){
return false
})
})
alert('oi!!')
}
else {
$('.navbar .dropdown > a ').each(function () {
$(this).on("click", function(){
location.href = this.href;
})
});
alert ("bad!") //for debugging purpose, not really needed
}
}).resize();
//the mobile menu clicks events
$('#menu .dropdown > a ').click(function () {
location.href = this.href;
});
});
PS this is a website, not an android app. I have found answers that answer this type of questions for android apps.
Update the jsfiddle for my code
I solved it myself. Turns out, the condition for width checking was creating the problem and in my case, unnecessary, because bootstrap is already hiding the menu in smaller screens and I was targeting touch enabled desktop devices anyway. so I took off && (o >= 990) from the if condition and it is working as expected.
full js is below (in case anyone needs it). I used the timer to prevent the event from firing before the resize, but it will probably work without the timer too. :
$(document).ready(function () {
var resizeTimer;
$(window).on('resize', function(e){
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function () {
function isTouchDevice() {
return true == ("ontouchstart" in window || window.DocumentTouch && document instanceof DocumentTouch);
}
if (isTouchDevice() === true) {
$('.navbar .dropdown > a ').click(function () {
return false
});
console.log("landscape")
}
else {
$('.navbar .dropdown > a ').each(function () {
$(this).on("click", function(){
location.href = this.href;
})
});
console.log("portrait")
}
}, 250)
}).trigger('resize');
});
I think this is a problem with the way you are recognizing the mobile device. For checking device sizes I would not suggest using $(window).innerWidth(). What you are doing now does not check the screen size, rather it checks the window size, which fluctuates when switching orientation.
I would like to suggest that instead of checking for only >900px, that you check for the entire area of the device (width x height) so landscape and portrait would act the same way. And I would like to suggest using screen.availHeight * screen.availWidth to determine this.
I really hope this helps you with your problem. Please let me know if not and I'll help you debug.

How to prevent duplicate events when scroll in jQuery?

I have 4 divs like;
<div class="diva">diva</div>
<div class="divb">divb</div>
<div class="divc">divc</div>
<div class="divd">divd</div>
They are 400px wide and high. I want to alert a when div b scrolls to top of page, and did using scroll function and scrollTop method. Each time when scroll, it check if scrollTop() if lager than 400, and alert a. But if I don't click the on the ok button of alert window, if I continue scrolling, multiple alerts will come, and I have to close them all.
But I just want one alert, and even if I continue scrolling, I want no more alerts. Also if the scrollTop is below 400px, I want to alert b (here also, I don't want repeats). If I got alert a, and if I scroll in opposite direction, and if scrollTop becomes below 400px, I want alert b, no problem for that.
Here is the fiddle.
please add this script on your file JS and try this script:
$(document).ready(function() {
$(window).scroll(function(){
var xx = $(document).scrollTop();
if(xx > jQuery(".divb").height()){
alert("a");
}else{
alert("b");
}
});
});
You are popping alerts on a 'scroll' event which happens every time you scroll..
if this is just a debugging annoyance, what you can do is use console.log('a') instead - example
If you wanted the actual function to run once for each time you reach it you can do this:
var a = false;
$(window).scroll(function(){
var xx = $(document).scrollTop();
if(xx > 400){
if (!a) {
alert("a");
a = true;
}
}else{
if (a) {
alert("b");
a = false;
}
}
});
fiddle for this example
The easiest way to avoid any confusion would be to keep state of scroll actions.
Demo: http://jsfiddle.net/abhitalks/uwUvC/1/
var last = 0, // last scroll-top to determine scroll direction
scrolledUp = false, // to cache state of scroll up
scrolledDown = false; // to cache state of scroll down
$(window).scroll(function (event) {
var current = $(this).scrollTop();
if (current > last) { // if scrolled down
if (current > 400 && !scrolledDown) { // check position and state
alert("A");
scrolledDown = true; // reset scroll down state
}
} else { // if scrolled up
if (current < 400 && scrolledDown && !scrolledUp) {
alert("B");
scrolledUp = true; // reset scroll up state
}
}
last = current; // keep current position to check direction
});
This way you are sure about when you are scrolling up and when you are scrolling down. Keep state of scroll in respective variables and check them.
The alerts fire only once in each direction.

Browser Viewport detection with plain JavaScript

I am using plain JavaScript code to detect browser viewport and which is as follows:
function setLocation(url) {
if (window.location.href.indexOf(url) === -1)
window.location = url;
}
function reloadPage(width) {
if (width < 701) {
setLocation("layout700.php");
} else if (width < 900) {
setLocation("layout900.php");
} else {
setLocation("layout1200.php");
}
}
var done = false;
function ready() {
if(!done) {
done = true;
reloadPage(document.width);
}
}
if(window.addEventListener) {
window.addEventListener('DOMContentLoaded', ready, false);
window.addEventListener('load', ready, false);
} else if(window.attachEvent) {
window.attachEvent('onload', ready);
}
window.onresize = function() {
reloadPage(document.width);
};
My question is : How can I define width range in this?
What I mean is.... Is it correct if I use as
function reloadPage(width) {
if (width <= 701 && >= 480) {
setLocation("layout700.php");
} else if (width <= 900 && >= 701) {
setLocation("layout900.php");
} else {
setLocation("layout1200.php");
}
}
If this is not correct then what is the correct syntax? Kindly help.
function reloadPage(width) {
if( width >= 480 ) {
if (width <= 701 ) {
setLocation("layout700.php");
} else if ( width <= 900 ) {
setLocation("layout900.php");
} else {
setLocation("layout1200.php");
}
}
}
What is changed from your code ?
- After the logical operator " && " you did not mention the variable name, which is incorrect.
- You need not check for " width > 701 " in the second condition, because, if it was <= 701, the first condition would have been satisfied.
EDIT : Added a wrapper if() to check the page is greater than 480, since you don't have any layouts specific to that.
Start at the largest and move to the smallest. Also, because setLocation should immediate halt execution, you can optionally leave out the "else" stuff. Finally, I assume if width is less than 900, you should go to layout700, even if the width is less than 700? It seems like it would be the closest-fit for a very thin browser.
if (width>1200) {
setLocation("layout1200.php"); }
if (width>900) {
setLocation("layout900.php"); }
setLocation("layout700.php");
I'd be tempted to borrow this (http://adactio.com/journal/5429/) technique that Jeremy Keith has just blogged about and use the content attribute to store the correct page for the relevant dimensions - you could then use media queries to differentiate between the various sizes.
Something else you might want to consider... is using Device Atlas or
WUFRL to detect the end users browser and serve them out the correct layout to start - redirects are poor experience for end users and particularly slow over mobile.

Categories