Test if page has a horizontal scrollbar (computer & mobile devices) - javascript

On a web page, I need to test if there is a horizontal scrollbar or not (so that I programmatically change the css of some other element). Is there some way to get that information using jquery (or pure javascript)?
I tested
function isHorizontalScrollbarEnabled() {
return $(document).width()!=$(window).width();
}
but it does not seem to work with all browsers (does not work for example with a recent Samsung phone I tested). I need it to work with all browsers, including recent mobile devices.
Thank you!
EDIT 1
I tested the solutions provided by plalx and laconbass, tested IE8, Firefox, Chrome and iPad. Works with IE, Firefox & Chrome but not as I want on the iPad.
The problem seems related to the zooming feature on mobile devices: even though, when I zoom in on the iPad, a horizontal scrollbar appears, document, window and document.body widths do not change (was also the same problem with the Samsung phone I tested earlier today).
Here is the code I used to test:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<title>test</title>
</head>
<body>
<div style="width: 500px; background: red;" id="test">click here to test</div>
<script type="text/javascript">
var i = 1;
$("#test").click(function(){
$(this).html("Test #" + (i++)
+ "<br>document width=" + $(document).width() + ", windows width=" + $(window).width()
+ "<br>document width=" + $(document).width() + ", body width=" + $(document.body).width()
);
});
</script>
</body>
</html>
Any idea how to detect the presence of a horizontal scrollbar that also works after zooming in/out on a mobile device like iPad?

//scrol 1px to the left
$(document).scrollLeft(1);
if($(document).scrollLeft() != 0){
//there's a scroll bar
}else{
//there's no scrollbar
}
//scroll back to original location
$(document).scrollLeft(0);
This works because JQuery won't be able to scroll the screen if no scrollbar is available

EDIT 2: I got a downvote because this doesn't work for nothing but the page so I built a generic solution based on #Pabs123's answer, only for fun:
function hasScrollX( selector ){
var e = $(selector), fn = 'scrollLeft';
return e[fn](1) && e[fn]() > 0 && e[fn](0) && true;
}
or even
jQuery.fn.hasScrollX = function( ){
var fn = 'scrollLeft';
return this[fn](1) && this[fn]() > 0 && this[fn](0) && true;
}
See it here, and how it can be easily adapted to detect vertical scrollbar presence.
EDIT: Tested & working on chrome and firefox. As jQuery team does the crossbrowsing work, i suggest the use of jQuery rather than native javascript.
I were curious about how to do this in an elegant way than the suggested previously (which actually work)
The following comparison work to me
$(document).width() > $(window).width()
you can see it in action with scroll bar and without it

Related

Resize eventListener Edge

I've currently encountered this issue on Microsoft Edge 44.18362.449.0 which I do not know how to solve.
I applied an event listener on the window in order to perform some resizing actions. This works perfectly on Chromium-based browsers and IE11. For some reason on Edge when I try printing out the window.innerWidth in the resize function it stops at 562px. This means the event listener does not trigger when the window size goes under 562px.
Did anyone encounter this issue before?
I try to test the below code with the MS Edge legacy browser 44.18362.449.0, IE 11 browser, and Google Chrome browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<div id="result"></div>
<script>
function displayWindowSize()
{
var w = window.innerWidth;
var h = window.innerHeight;
document.getElementById("result").innerHTML = "Width: " + w + ", " + "Height: " + h;
}
window.addEventListener("resize", displayWindowSize);
displayWindowSize();
</script>
</body>
</html>
Output:
Based on my test result, I noticed that the MS Edge legacy browser can minimum show the 562 px of window width but user can still decrease the size by resizing the window width but the MS Edge legacy browser will keep displaying the width 562 px.
Generally, the browsers stop resizing at some point and it shows that value as a height or width. Here, the issue is that the MS Edge legacy browser shows the minimum 562 px of width but the user can still decrease the window width.
I suggest you press ALT + J key in the MS Edge legacy browser window and it will launch the Feedback hub. You can try to provide feedback regarding this issue.

Detect if mobile - if yes use java01.js , if not mobile use java02.js

Complete beginner (hobbyist) here so this is probably a total noob question.
I have two javascripts. One is for mobile users, other is for desktop users.
Right now I have in my html:
<script type="text/javascript"
src="../java_file.js">
</script>
It works wonderfully but I want to have a different js file run when screen width is less than 480.
I want to do something along these lines:
<script type="text/javascript"
if (screen.width < 480) {
src=".../java_file_mobile.js">
}
else {
src=".../java_file.js">
}
</script>
This is my first time building a site and I'm learning the code as I go. Any assistance would be great. Thanks!
If you only care about the screen width the simplest approach is to use JavaScript offsetWidth.
var w = document.body.offsetWidth;
if ( 480 > w ) {
//append mobile script
} else {
//append desktop script
}
Beaver though, a small offsetWidth could also just mean a narrow browser window on a desktop screen. Or a watch. Or a fridge. You get the idea...

Ipad: window.height() give bad value in Safari but not in Chrome

I have to get the window's height on Ipad to display something in the full height.
I have done this example page: http://daviddarx.com/stuffs/work/biceps/ipad/
Here is my js code, very simple, that only write the window.height() in the body:
generalResizeListener=function(){
screenW=$(window).width();
screenH=$(window).height();
$("body").html(screenH)
console.log(screenH);
}
$(window).resize(generalResizeListener);
There is two problem, on my ipad2 with IOS7:
-In safari, but not in Chrome, the displayed value don't fit to the actual page height (I checked on screenshots)
-In Safari always, even if there isn't anything in the page, the page's height is bigger than the viewport and I can scroll down for something like 10-20px. That is the biggest probleme.
Do you know why is this happening? I haven't any css files in my demo page, so I really don't understand.
Thank you in advance for your help!
David
#Gal V:
I already implemented this "hacky solution". Thank you for your answer, anyway! I looked a bit more in google and it seems to be a specific bug of safari IOS7:
-https://discussions.apple.com/message/23150650#23150650
-Scrolling problems on a web page with fixed header and footer in iOS7
-iOS 7 iPad Safari Landscape innerHeight/outerHeight layout issue
Safari browser on iOS has a bottom bar (unlike chrome) that is being calculated inside the window height while it isn't really part of the window/page.
you need to detect cases (with user-agent) where the client uses Safari browser on iOS device, and then you need to set the height of the body (with javascript) to $(window).height() - bar_height, and it should solve your problem.
hope that helps.
My solution is this...
Insert this on your page:
<div id="win-height" style="position: fixed;left: 0; top: 0; bottom:0; width: 0; z-index: "></div>
instead of,
$(window).height()
to get the window height, use,
$('#win-height').height()
Goodluck!
I used this JavaScript solution for solving that problem:
if (navigator.userAgent.match(/iPad;.*CPU.*OS 7_\d/i) && window.innerHeight != document.documentElement.clientHeight) {
var fixViewportHeight = function() {
document.documentElement.style.height = window.innerHeight + "px";
if (document.body.scrollTop !== 0) {
window.scrollTo(0, 0);
}
}.bind(this);
window.addEventListener("scroll", fixViewportHeight, false);
window.addEventListener("orientationchange", fixViewportHeight, false);
fixViewportHeight();
document.body.style.webkitTransform = "translate3d(0,0,0)";
}

Jquery $(window).height() function does not return actual window height

I have a page that I need to dynamically load ajax content when the user scrolls to the bottom. The problem is that JQuery is not returning the correct window height. I have used this function before and have never seen it fail, but for some reason it will return the same value as the document height. I have the test page here: bangstyle.com/test-images
I have coded the alert to display at page load, and also whenever the user scrolls 500px below the top:
function scroller() {
if($(window).scrollTop() > 500){
delay(function(){ //200ms wait
pagecounter++;
sideshow();
alert("window height: " + $(window).height() + " scrolltop: " + $(window).scrollTop() + " document height: " + $(document).height());
return false;
}, 200 );
}
}
I tried posting this before but I deleted it as I didn't get a solution. I hope it is ok to post a link to my test page. BTW I have tested this on Mac Safari and Mac FF. I have run this same code on other pages and it works fine. I feel there must be something in the dom of this page that causes JS to fail, but no idea what that would be.
Look at your HTML souce code.
The first line should be <!DOCTYPE html> and you have <style> tag instead.
So it seems that your document is running in Quirks Mode and jQuery can't calculate correct window dimensions.
//works in chrome
$(window).bind('scroll', function(ev){
//get the viewport height. i.e. this is the viewable browser window height
var clientHeight = document.body.clientHeight,
//height of the window/document. $(window).height() and $(document).height() also return this value.
windowHeight = $(this).outerHeight(),
//current top position of the window scroll. Seems this *only* works when bound inside of a scoll event.
scrollY = $(this).scrollTop();
if( windowHeight - clientHeight === scrollY ){
console.log('bottom');
}
});
I had the same problem.
I've found some things:
1) the problem happens when you try to get the actual height before document is completed rendered;
2) the problem happens in google chrome when you does not use corret DOCTYPE (mentioned above)
3) it always happens in google chrome even after the document is rendered completly.
For google chrome, I've found a workaround here: get-document-height-cross-browser
I'm using this solution only for google chrome and it resolved my problem, I expect helps someone that still have the problem.
This is an old question but I recently struggled with not getting the correct window height in IE10 by a few pixels.
I discovered that IE10 applies a 75% zoom by default and that screws the window and document measurements.
So, if you're getting wrong width or height, make sure zoom is set to 100%.
Did some looking around and stumbled upon this, don't know if it helps but it's worth bringing up.
why is $(window).height() so wrong?
Since jquery (and dom in general) is not calculating sizes correctly in quirksmode, two solutions:
Add doctype html at the top of your page (like mentioned in "correct" answer), or
Use window.innerHeight, window.innerWidth if first option is not an option.
Hope it helps.
I moved my scripts from to footer and that resolved it for me.

How do I keep a bar on the bottom of a page in IE 6,7,8 or how do I force IE to redraw the interface?

I need to glue a bar to the bottom of the client view in the web browser. Traditionally I would use position:fixed; except that I need to support my IE 6 clients. I've got a very extensive hack to glue the bar to the bottom of the page and over the content, however when the user scrolls down or right, the bar stays fixed on the page.
To correct this issue I use a javascript event that gets fired using setInterval and when running the function in IE (8)'s debug tools the event fires and changes the position top and position left attributes but the page doesn't redraw the element. The code works but the element is not moving, see below.
Just so you know, the fix has to work in IE quirks mode... it can't work if the other IE versions are trying to use a standard. Believe me, I've tried.
P.S. This is really aggravating because I'm double checking IE9 support as well... get this the element does not move with the scroll bars in IE 6, 7, and 8 but moves in IE 9 and it still displays "IE Quirks Mode." And Microsoft said that this release wouldn't effect anything,...
HTML Structure
<body>
<div id="j_zoom_area" style="zoom:100%;">
The Application area the the zoom is changed (by the bar) for accessibility...
</div>
<div id="j_protectorite">
<div class="j_bar">
<div class="j_plate">Zoom Controls, Help, Search, other misc controls</div>
<div class="j_plate">Copyright info, privacy policy, etc...</div>
</div>
</div>
<script type="text/javascript" language="javascript">
j_doBar();
</script>
</body>
The CSS for the bar is https://kscserver.com/ERP-API/Style/includes.css.
The particular javascript for the bar correction.
//This controls the scrolling of the bar
function j_FixBarSlowly(){
var nTop = 0;
var nLeft = 0;
nTop = (document.body.scrollTop + document.body.clientHeight) - 67;
nLeft = document.body.scrollLeft;
//document.title = document.body.scrollTop + '+' + document.body.clientHeight + '-67' + '=' + nTop + 'px';
document.getElementById("j_protectorite").style.Top = nTop + 'px';
document.getElementById("j_protectorite").style.Left = nLeft + 'px';
document.getElementById("j_protectorite").style.Bottom = '';
document.getElementById("j_protectorite").style.Position = 'absolute';
//Ie6,7,8 hack to force redraw
}
function j_doBar() {
//j_FixBarSlowly();
//if (setInterval != undefined) {
// setTimeout("j_doBar();",5);
//} else {
setInterval("j_FixBarSlowly();",5);
//}
}
I'd suggest using an IE fix hack, such as Dean Edwards' IE7.js.
This script runs when your page loads in IE and fixes some common problems in older versions of IE. The documentation lists the things it deals with, and includes position:fixed;.
Hope that helps.
(Of course, the best solution - for your sanity - is just to give up trying to make IE6 look identical to newer browsers, and just live with a non-sticky footer in IE6. As long as it doesn't affect usability, I don't see a problem with IE6 users having a slightly less perfect page layout. But I know some people don't have the luxury of doing that; if your users are demanding it, they're the ones you have to listen to, not me!)
After further testing the best solution was to use an I Frame for the page content and have a div at the bottom of the page content. Of course a few javascript tweaks for proper sizing and you have a perfect solution.
Just for a visual reference.

Categories

Resources