Im using this to run some code when a browser window is resized: $(window).resize(callback)
I also need to run this code when the orientation is changed in phones and tablets. Will the above fire on this event?
Some devices/browsers do, some not. You need to decide your supported browsers and devices.
If you want to be on secure side you should use the resize event and get/check the sizes inside in it; if you know your desired devices go with a simple orientation change:
Easy solution:
// Listen for orientation changes
window.addEventListener("orientationchange", function() {
// Announce the new orientation number
alert(window.orientation);
}, false);
More secure/supported
// Listen for resize changes
window.addEventListener("resize", function() {
// Get screen size (inner/outerWidth, inner/outerHeight)
}, false);
David Walsh wrote a good article about resize and orientation change event.
More about orientation change and sizes here:
http://davidwalsh.name/orientation-change
the answer is imho: no
but:
$(window).on('resize orientationchange', function(){
//do stuff
});
should have you covered
careful, this can trigger twice depending on the browser
My solution:
Generate an event when orientationchange doesn't do it
use a throttle to prevent to much update on resize (lodash library for instance)
window.addEventListener("resize", throttle(function() {
//to do when resize
}, 50), false);
window.addEventListener("orientationchange", function() {
// Generate a resize event if the device doesn't do it
window.dispatchEvent(new Event("resize"));
}, false);
Quirksmode directly tested this question and found that the native resize event fired on orientation change in all browsers other than Opera Mini: https://www.quirksmode.org/dom/events/resize_mobile.html
A simple solution is to pass a value based on the event type..
window.addEventListener('resize', function () {
myFunction('resize');
});
window.addEventListener("orientationchange", function() {
myFunction('orientation');
});
function myFunction(value) {
if (value == 'resize') {
// do something
} else if (value == 'orientation') {
// do something else
}
}
since orientationchange event has been deprecated, it's now possible to use screen.orientation.onchange
Deprecated: Window: orientationchange event
i.e.
const resizeScreen = debounce(async () => {
await animateWithNewDimensions();
}, 50);
window.screen.orientation.onchange = resizeScreen;
https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation#browser_compatibility
Too bad Safari is not supporting this :/
Related
in my js code I have pretty simple event listener listening for a click -
element.addeventlistener('click', ()=>{
#do somthing
})
the issue is that when I am scrolling on IOS (iphone) - touching this element to start the scroll, triggers the event listener.
Is there a way to prevent a event listener on iphone, unless no scrolling is to follow?
i.e. do something if clicked but scrolling doesn't follow
alternatively the might be a completely different solution (but I am trying to avoid a library)
thanks
W
ANSWER
After reviewing the answer given below (which does work) as described, this issue was still persisting. This gave me cause to review my CSS on which I found that on IOS mobile (iphone) - the CSS psudo selector :focus is activated when you scroll over an item.
I added a media query to only allow :focus to be used on desktop size devices or above, which solved the issue.
I have a found a possible solution on another question in Stackoverflow: Question
Basically you add a scroll listener to your window. This will then set a global boolean called disable_click_flag to true when scrolling. If the user wasn't scrolling for at least 250ms it will be set to false.
When the boolean is true then the click event isn't able to go trough.
var disable_click_flag = false;
var timeout = null;
window.addEventListener('scroll', () => {
disable_click_flag = true;
if(timeout) clearTimeout(timeout);
timeout = setTimeout(function(){ disable_click_flag = false }, 250);
}
element.addeventlistener('click', () => {
if(disable_click_flag === false{
#do somthing
}
})
I'm not an expert, but I would try:
var prevScroll = pageYOffset;
window.addEventListener("scroll", () => prevScroll = pageYOffset);
window.addEventListener("click", (e) => {
if (pageYOffset !== prevScroll) return;
// your code
});
Please note that this code is not tested, however I think it should work.
Upon load, I am positioning the users scroll to the top of the '#gallery-view' element.
This is working correctly on iPad and iPhone. However, if I change the orientation of the device, its not positioning.
I have run tests to check the code is run on orientation change. The 'resize' option is triggering correctly and the 'test' console.log is output.
Here is the code:
jQuery.noConflict();
function winResize() {
if ( jQuery('#gallery-view').length ) {
console.log('test');
window.setTimeout(function() {
window.scrollTo(0, jQuery('#gallery-view').offset().top);
}, 0);
}
}
jQuery(window).on('load', function() {
jQuery(window).resize(winResize);
winResize();
});
Does anyone know of any reason why this wouldn't trigger on orientation change?
Try attaching your winResize handler function to the orientationchange event as well. See the MDN docs.
Holdable button works on desktop, but doesn't work on mobile
clicker.mousedown(function(){
timeout = setInterval(function(){
clicker.text(count++);
}, 500);
return false;
});
http://jsfiddle.net/8FmRd/
what's wrong?
To do it by actual hold, you'd do something like:
var timeoutContainer;
// this should work with mouse only
$el.on('mousedown', function(ev) {
if(ev.type=='click'){
timeoutContainer = setInterval(function(){
// your stuff.
}, timeToHold);
}
});
$el.on('mouseup', function(ev) {
clearInterval(timeoutContainer);
});
// or, if you only want to apply it to touch.
$el.on('touchstart', function(ev) {
timeoutContainer = setTimeout(function(){
// your stuff.
}, timeToHold);
});
$el.on('touchend', function(ev) {
clearTimeout(timeoutContainer);
});
After looking at your fiddle, it may not be working as expected because of touchcancel. I noticed you have document.mouseup. It might be treating moving finger as a mouse up or something. If you do it explicitly as touch start it may behave differently. You'd need to check for mobile before as above in the mouse down part.
You need to use touchstart and touchend events to detect a touch on a button on mobile devices. On some devices touchmove might also trigger so you can also check for that.
https://developer.mozilla.org/en-US/docs/Web/API/Touch_events
I am trying to trigger an event in a web browser on a desktop
$(window).trigger('resize');
The issue is on mobile it doesn't seem to be triggering. Is there an alternative method for mobile?
I am using tablesaw plugin for grids. When the screen is small in size, the columns will not fit and as such a swipe will be provided to move between them. When I sort them, all the columns gets squeezed and shown on the small screen, but after I trigger the resize event, an event in the plugin will get called that will fix them. On the mobile, this event doesn't exist I guess and I'm not targeting the orientation.
a variation of this (JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?)
this will run on resize and orientchange.
var waitForFinalEvent=function(){var b={};return function(c,d,a){a||(a="THISPAGE");b[a]&&clearTimeout(b[a]);b[a]=setTimeout(c,d)}}();
var fullDateString = new Date();
$(document).ready(function(){
$.resized = function(){
waitForFinalEvent(function(){
//function to run
}, 300, fullDateString.getTime())
}
window.addEventListener("orientationchange", function() {
$.resized();
});
$(window).resize(function () {
$.resized();
});
$.resized();
});
window.dispatchEvent(new Event('resize'));
Is there any way with jQuery or JavaScript to trigger a function when the user ends to resize the browser window?
In other terms:
Can I detect mouse up event when user is resizing the browser window? Otherwise:
Can I detect when a window resize operation is finished?
I'm currently only able to trigger an event when the user start to resize the window with jQuery
You can use .resize() to get every time the width/height actually changes, like this:
$(window).resize(function() {
//resize just happened, pixels changed
});
You can view a working demo here, it takes the new height/width values and updates them in the page for you to see. Remember the event doesn't really start or end, it just "happens" when a resize occurs...there's nothing to say another one won't happen.
Edit: By comments it seems you want something like a "on-end" event, the solution you found does this, with a few exceptions (you can't distinguish between a mouse-up and a pause in a cross-browser way, the same for an end vs a pause). You can create that event though, to make it a bit cleaner, like this:
$(window).resize(function() {
if(this.resizeTO) clearTimeout(this.resizeTO);
this.resizeTO = setTimeout(function() {
$(this).trigger('resizeEnd');
}, 500);
});
You could have this is a base file somewhere, whatever you want to do...then you can bind to that new resizeEnd event you're triggering, like this:
$(window).bind('resizeEnd', function() {
//do something, window hasn't changed size in 500ms
});
You can see a working demo of this approach here
Another way of doing this, using only JavaScript, would be this:
window.addEventListener('resize', functionName);
This fires every time the size changes, like the other answer.
functionName is the name of the function being executed when the window is resized (the brackets on the end aren't necessary).
This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:
window.onresize = functionRef;
The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)
function resize() {
console.log("height: ", window.innerHeight, "px");
console.log("width: ", window.innerWidth, "px");
}
window.onresize = resize;
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
If You want to check only when scroll ended, in Vanilla JS, You can come up with a solution like this:
Super Super compact
var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }
All 3 possible combinations together (ES6)
var t
window.onresize = () => {
resizing(this, this.innerWidth, this.innerHeight) //1
if (typeof t == 'undefined') resStarted() //2
clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}
function resizing(target, w, h) {
console.log(`Youre resizing: width ${w} height ${h}`)
}
function resStarted() {
console.log('Resize Started')
}
function resEnded() {
console.log('Resize Ended')
}