I'm setting up some simple booleans that test for mobile layouts and touch devices, but I'm having some difficulty making the code more compact.
isTouch tests for touch devices.
mobile tests for when the screen width is below 769px.
My final if/else statement is to test if I'm on a mobile touch device (iPad, phone, whatever). I can alert the output and everything is expected, but the static_element still appears instead of swiper_element. I know I'm missing something with my booleans.
Help a rookie out?
$(document).ready(function () {
var windowWidth,
isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0)),
mobile,
touchDevice;
$(window).on('load resize', function () {
windowWidth = $(window).width();
if (windowWidth < 769) {
mobile = true;
} else {
mobile = false;
}
if (isTouch = true) {
touchDevice = true;
} else {
touchDevice = false;
}
});
if (touchDevice && mobile) {
$('.static_element').hide();
$('.swiper_element').show();
} else {
$('.static_element').show();
$('.swiper-element').hide();
}
});
The swiper thing is not working, because there is a dash instead of an underscore in the last line of your code. And yes, you could simplify a few things (see the code below). I moved all mobile detection logic to a function, so we can reuse it anytime we want.
Note: Mobile detection is an art – mainly because there are many devices and use cases. Querying the "ontouchstart" capability works fine for most of the devices, it won't work on some devices. That's why I added the console.log, so you can check if the right code block is executed.
$(document).ready(function () {
var isTouch,
isMobile;
// Initially call the function to set isTouch and isMobie
detectMobile();
// If the window is reloaded or resized check again
$(window).on('load resize', detectMobile);
// Set the booleans when called
function detectMobile() {
// Always evalutes to true or false
isTouch = ('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0);
// Always evalutes to true or false
isMobile = $(window).width() < 769;
}
if (isTouch && isMobile) {
// Logs the actual status to the console
console.log("I'm a mobile device!");
$('.static_element').hide();
$('.swiper_element').show();
} else {
// Logs the actual status to the console
console.log("I'm a boring normal device!");
$('.static_element').show();
$('.swiper_element').hide();
}
});
Change your codes into this:
$(document).ready(function () {
var windowWidth,
isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0)),
mobile,
touchDevice;
$(window).on('load resize', function () {
windowWidth = $(window).width();
if (windowWidth < 769) {
mobile = true;
} else {
mobile = false;
}
if (isTouch) {
touchDevice = true;
} else {
touchDevice = false;
}
});
if (touchDevice && mobile) {
$('.static_element').hide();
$('.swiper_element').show();
} else {
$('.static_element').show();
$('.swiper-element').hide();
}
});
Related
I have this code and everything works good, but when I open my search bar on mobile and click on input field, my keyboard opens and closes, I found that window.resize is the problem, but I haven't found any fixes for this, what should I do?
function appendSearchBar() {
if($(window).width() <= 769){
$('.search-bar').appendTo('.mobile-toolbar .global-search');
} else {
$('.search-bar').appendTo('.header-toolbar-nav .global-search');
}
}
$(window).resize(function() {
appendSearchBar();
});
When you appendTo the element is detach and re-attached to the DOM and thus loses focus.
You should only append if it is not where you want it.
let inMobile;
function appendSearchBar(firstTime) {
const windowWidth = $(window).width();
if (windowWidth <= 769 && (!inMobile || firstTime)) {
inMobile = true;
$('.search-bar').appendTo('.mobile-toolbar .global-search');
}
if (windowWidth > 769 && (inMobile || firstTime)) {
inMobile = false;
$('.search-bar').appendTo('.header-toolbar-nav .global-search');
}
$(window).resize(function() {
appendSearchBar();
});
appendSearchBar(true);
Please Guys i need assist with this project:
I am a bit confused rn, i wanted this piece of code to display a specific styled div modal designed for a specific browser. What i want is: if browser is firefox modal displays "On My Way Home", styled with a class .home. else if my browser is chrome, display a modal "Home Now"
Thanks
$(function(){
function modal() {
var options = {
trigger: '.lp-download-btn',
selectorClose: '.close',
selectorContent: '#j-download-instructions',
selectorLinks: 'a',
chromes: '.chrome'
};
var $body = $(options.selectorContent);
var $chromeBrowser = $(options.chromes);
$('body').on('click', options.trigger, function() {
$body.css({
height: '100%',
width: '100%',
visibility: 'visible'
});
})
$body.on('click', function(e){
if (this == e.target) {
$body.hide();
return false;
}
});
$body.on('click', options.selectorClose, function(){
$body.hide();
return false;
});
$body.on('click', function() {
$chromeBrowser.css({
display: 'block'
})
})
}
function browserDetection() {
// IE or not
if (navigator.userAgent.search("MSIE") >=0 ){
return modal();
}
// Chrome browser
else if (navigator.userAgent.search("Chrome") >= 0) {
return modal();
}
// Firefox Browser
else if (navigator.userAgent.search("Firefox") >= 0) {}
// Safari browser
else if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {}
// Opera browser
else if (navigator.userAgent.search("Opera") >= 0) {}
}
browserDetection();
});
You can perform user agent sniffing to possibly detect which browser someone is in, although it does have drawbacks https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent but in this case you can use that to do what you would like.
I want to detect a device width and height (responsive layout), so if return is true I want to toggle class "mobile" but I'm doing something wrong and I don't know what.
$(function detectmob() {
if(window.innerWidth <= 720 && window.innerHeight <= 1280) {
return true;
} else {
return false;
}
if (return=true) {
$(document).getElementByClass("box").addClass ('mobile');
}
}
Instead of returning true, you could just add the class there
return will exit out of the function from when it is encountered. You are looking for a variable isolated to detectmob based on which a class can be added.
function detectmob() {
var isMobile = false;
if (window.innerWidth <= 720 && window.innerHeight <= 1280) {
isMobile = true;
}
if (isMobile) {
$(document).getElementByClass("box").addClass('mobile');
}
}
But if you still want to check based on the return value then the logic has to be extracted out into a function which can have a return value.
function detectmob() {
var isMob = isMobile();
if (isMob) {
$(document).getElementByClass("box").addClass('mobile');
}
}
function isMobile() {
return window.innerWidth <= 720 && window.innerHeight <= 1280;
}
You should use user agent instead of screen size otherwise mobile with a huge resolution will be detected as PC (eg Pixel 2 XL have 1440 x 2880 screen). Also user may resize browser window on PC to 700x1000 and your code will detect it as mobile.
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;
}
I'm trying to detect orientation changes on mobile devices and trigger a function once an orientation has been completed, but the code inside the function is continuously firing in Android and I'm not sure why. Here's my code:
var supportsOrientationChange = "onorientationchange" in window;
var orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
window.addEventListener(orientationEvent,
function() { alert ('orientation changed'); },
false
);
Does anyone know how to write this so that it only triggers once, after orientation change has been completed?
I used a work-around for this in my app. I added an event listener for orientationchange and then set a timeout so the orientationchange could occur and I could get a new width value that actually reflected the width after the orientation change.
var device_width = 0;
$(document).ready(function () {
var oc_timer;
$(window).bind('orientationchange', function () {
clearTimeout(oc_timer);
oc_timer = setTimeout(function () {
device_width = $(window).width();
}, 500);
});
});
I am not positive this will solve your continuously firing function problem but this is a solution I found to work.
I found a way to do this in case others are still having the same issue, check it out:
function onOrientationChange() {
if (typeof(this.orientation) === "undefined"){
if (window.orientation == -90 || window.orientation == 90) {
this.orientation = "landscape";
} else {
this.orientation = "portrait";
}
// alert ("in 1");
// you code here for change
}
if ((window.orientation == -90 || window.orientation == 90) && (this.orientation == "portrait")) {
this.orientation = "landscape";
// alert ("in 2");
// you code here for change
}
if ((window.orientation == 0 || window.orientation == 180) && (this.orientation == "landscape")) {
this.orientation = "portrait";
// alert ("in 3");
// you code here for change
}
}
Simple solution for less detailed applications
//bind orientation change event
$(window).bind("orientationchange", orientationChange);
//later,
function orientationChange(){
//whatever needs to happen when it changes.
alert("changed");
}
You could also use $.on() instead if you need to pass information.
In browsers that do not support it, the event does not fire. You could then write a custom detection script as a fallback to fire the event if the orientation changes on a device that does not support onorientationchange.