How to get device rotation for iPhone 7 in javascript? - javascript

I want to get the device rotation for (alpha, beta, gamma) for iPhone 7 and higher. For iPhone 6 this works well for me:
window.addEventListener('deviceorientation', function(event) {
console.log(event.alpha);
console.log(event.beta);
console.log(event.gamma);
});
But for iPhone > 6 this event is not triggered anymore. To be clear, i dont want the device orientation (portrait/landscape), I want the rotation. Best case would be absoulte (calibrated) data.
For Android "deviceorientationabsolute" works well. Is there something similar for the Apple universe?
Thanks & regards,
Andreas

for get device rotation in all devices better listen on resize window:
window.addEventListener('resize', function(){
if(window.innerWidth < window.innerHeight){
//portrait
}
if(window.innerWidth > window.innerHeight){
//landscape
}
});

Ok, the solution for me was to get the user permission to use orientation like this. After that 'ondeviceorientation' works.
function startOrientation() {
if (typeof DeviceMotionEvent.requestPermission === 'function') {
DeviceOrientationEvent.requestPermission().then(function(response) {
if (response == 'granted') {
console.log('granted');
}
});
} else {
console.log('not granted');
}
}
$("#get_permission").click(function(){
startOrientation();
});

Related

mousewheel event not working on firefox

Below code is working fine on chrome however it doesn't work on Mozilla for some reason that I am not aware yet. Am i missing something ?
$(window).bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
$('#currentMove').html('Movement: Scroll up');
$('#currentMove').css('background','#98FB98');
scrollUp++;
$('#scrollUp').html(scrollUp);
}
else {
$('#currentMove').html('Movement: Scroll down');
$('#currentMove').css('background','#FFB6C1');
scrollDown++;
$('#scrollDown').html(scrollDown);
}
});
Here is my fiddle: https://jsfiddle.net/w0wffbxc/ Appreciate your help with this.
Here's your sqlfiddle fixed.
You should use wheel as mousewheel is not recognized by Firefox since version 3. Also with wheel, you should use event.originalEvent.deltaY instead.
Use wheel event instead. Its more of a standard now. This page also provides polyfills for old browsers https://developer.mozilla.org/en-US/docs/Web/Events/wheel
Ex
$(window).on('wheel', function(event){
// deltaY obviously records vertical scroll, deltaX and deltaZ exist too
if(event.originalEvent.deltaY < 0){
// wheeled up
console.log("Works Up");
}
else {
// wheeled down
console.log("Works Down");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jquery on scroll event is only triggered after scrollend (iOS 9.3)

I have a pretty annoying issue that (according to several sources, here is one) was already solved with iOS 8.
I am using $(window).scroll(function({ /*do stuff*/ }) to check if an element is on the screen and if that is the case something else happens. Pretty simple stuff. But it seems like that iOS devices "render" the stuff that the jQuery does only after the scroll has finished.
Here is a snippet of the code:
if($(window).width() < 601) {
$(".revealer-box").show();
$(window).scroll(function() {
if( isOnScreen(".revealer-box") ) {
if(flagCallG) {
$(".some-element").css("display", "flex");
$(".some-element").css("display", "-webkit-flex");
/* other unimportant stuff*/
flagCallG = false;
} else {
$(".some-element").css("display", "flex");
$(".some-element").css("display", "-webkit-flex");
}
} else {
$(".some-element").css("display", "none"); }
});
}
I use the iOS simulator on the Mac and also tried it on a real device. You scroll down and after you lift your finger the changes get visible.

Check for Touch device with Javascript

I have 3 buttons with hover states which makes a little tooltip appear to describe the button. They work fine but on touchs screen they do not disappear after the user clicks on the button.
So I've tried a few js scripts for checking if a device is a touch device or not. They almost work but they also when I test on IE11 it also gets detected as a touch device. Chrome & Firefox do not get mistaken as a touch device.
Any sugestions?
Her is what I've tried
/*****************************
TOUCH DEVICES HOVER FIX START
****************************/
// http://stackoverflow.com/a/4819886/1814446
function isTouchDevice() {
return 'ontouchstart' in window // works on most browsers
|| 'onmsgesturechange' in window; // works on ie10
};
// http://www.stucox.com/blog/you-cant-detect-a-touchscreen/#poke-it
var hasTouch;
window.addEventListener('touchstart', function setHasTouch () {
hasTouch = true;
// Remove event listener once fired, otherwise it'll kill scrolling
// performance
window.removeEventListener('touchstart', setHasTouch);
}, false);
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js
define(['Modernizr', 'prefixes', 'testStyles'], function( Modernizr, prefixes, testStyles ) {
// Chrome (desktop) used to lie about its support on this, but that has since been rectified: http://crbug.com/36415
Modernizr.addTest('touchevents', function() {
var bool;
if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
var query = ['#media (',prefixes.join('touch-enabled),('),'heartz',')','{#modernizr{top:9px;position:absolute}}'].join('');
testStyles(query, function( node ) {
bool = node.offsetTop === 9;
});
}
return bool;
});
});
if(bool===true) {
console.log('Touch Device'); //your logic for touch device
jQ( "#btn-1, #btn-2, #btn-3" ).click(function() {
jQ("#btn-1 .tooltip").css('opacity', '0');
jQ("#btn-2 .tooltip").css('opacity', '0');
jQ("#btn-3 .tooltip").css('opacity', '0');
});
}
else {
//your logic for non touch device
}
For IE10+ you can utilize "window.navigator.msMaxTouchPoints"
example code
function isIETouch ()
{
return window.navigator.msMaxTouchPoints == undefined ? false : window.navigator.msMaxTouchPoints;
}

Check if pause() exists in <video> (Safari 5.1.7 on Windows - HTML5 videos)

Safari 5.1.7 on Windows doesn't support play(), pause() etc. on video elements when Quicktime is not installed.
Therefore, I'd like to detect if it's supported or not.
jQuery('video').each(function(){
this.pause();
});
This returns: TypeError: 'undefined' is not a function (evaluating 'this.pause()')
jQuery('video').each(function(){
if( <<I need a way to check if pause is in this>> ){
this.pause();
}
});
I'm looking for a way to do this properly. Any help would be much appreciated!
How about some feature detection:
if (this.pause) {
this.pause();
}
You could even test if it is a function:
if (this.pause && Object.prototype.toString.call(this.pause) === '[object Function]') {
this.pause();
}
jQuery('video').each( function () {
if (this.pause) { //use it as a truthy check
this.pause();
}
});

Javascript to detect if user changes tab

I am writing a webpage for online quiz. The basic requirement I have is that it must fire an event(stopping the quiz) if the user changes tabs or opens a news window even without minimizing their browser, i.e if the person is attempting to see the answer from some other window/tab. How can I do that?
Note : Try to avoid including a bleeding edge HTML5 feature in your answer because I want the feature to be supported by all major browsers currently.
You can determine if a tab or window is active by attaching a blur / focus event listener to window.
in jQuery it would be
$(window).focus(function() {
//do something
});
$(window).blur(function() {
//do something
});
quoted from this SO answer: https://stackoverflow.com/a/1760268/680578
In 2022 you can use an event listener with the visibilitychange event:
document.addEventListener("visibilitychange", (event) => {
if (document.visibilityState == "visible") {
console.log("tab is active")
} else {
console.log("tab is inactive")
}
});
If you are targeting browsers that support it, you can use the Page Visibility API available in HTML5. It doesn't directly detect tab changes, per-say, but visibility changes. Which would include (but not limited to) tab changes.
See https://developer.mozilla.org/en/DOM/Using_the_Page_Visibility_API
Best native function hands down, no jQuery.
document.hasFocus
Check the pen, check what happens when you go to the link and back to the codepen tab.
https://codepen.io/damianocel/pen/Yxxzdj
With jQuery:
$(window).on('focus', function () {
});
$(window).on('blur', function () {
});
$().focus & $().blur are deprecated.
window onfocus and onblur work just fine:
window.onfocus = function (ev) {
console.log("gained focus");
};
window.onblur = function (ev) {
console.log("lost focus");
};
Working on a similar project. This worked the best. On the highest level component which wouldn't normally rerender, add:
setInterval( checkFocus, 200 );
function checkFocus(){
if(document.hasFocus()==false){
//Do some checking and raise a red flag if this runs during an exam.
}
}
I needed something like this and it seems this behavior is slightly different on each browser.
if (document.hidden !== undefined) { // Opera 12.10 and Firefox 18 and later support
visibilityChange = "visibilitychange";
} else if (document.mozHidden !== undefined) {
visibilityChange = "mozvisibilitychange";
} else if (document.msHidden !== undefined) {
visibilityChange = "msvisibilitychange";
} else if (document.webkitHidden !== undefined) {
visibilityChange = "webkitvisibilitychange";
} else if (document.oHidden !== undefined) {
visibilityChange = "ovisibilitychange";
}
document.addEventListener(visibilityChange, function(event) {
handleVisibilityChange();
}, false);
I have an example you can check:
https://jsfiddle.net/jenol/4g1k80jq/33/

Categories

Resources