$(window).resize not firing function properly on height/width condition - javascript

I have a fixed-positioned full-screen image gallery. The container div height is set via jQuery, and the next div (#page) has a margin-top equal to window.height.
Here is this code:
var windowH = $(window).height();
var windowW = $(window).width();
function marginTop() {
var currentH = $(window).height();
$("#page").css("margin-top", currentH +'px');
$("#image-gallery").css("height", currentH +'px');
console.log('mTop fired!');
};
$(window).resize(function() {
var newH = $(window).height(); // Records new windows height after resize
var newW = $(window).width();
var maxH = windowH + 90; // Sets a positive delta of some px
var maxW = windowW + 60;
var minH = windowH - 90; // Sets a negative delta of some px
var minW = windowW - 60;
if(newH > maxH) { // If the height difference is more than 50px, then set new marginTop for #page
marginTop();
console.log('fire for bigger height');
} else if(newH < minH) {
marginTop();
console.log('fire for smaller height');
} else if(newW > maxW) {
marginTop();
console.log('fire for bigger width');
} else if(newW < minW ) {
marginTop();
console.log('fire for smaller width');
}
});
I've split the conditions in several else if statement because it didn't work fine, and I had to check out when it was working, when not.
The various if...elseif...elseif... solve a problem on mobile browsers: without that delta, the #image-gallery div would change dimension when the address bar appears or disappears, resulting in stuttering adjustments of the div's height. Moreover, i did not want to redraw the whole thing for small changes in viewport on desktop too.
However it has some problem, as it doesn't work correctly. In particular:
marginTop() is fired only for window.resize with smaller height (checked from console.log)
on desktop, if the window is resized through the top-right-corner button, it doesn't fire at all.
removing all the if-else-if conditions, it works fine on desktop in any situation (but the address-bar is still a problem on mobile)
Can't figure it out, the code seems fine to me, but not to browsers. Where's the catch?
Tested on Firefox and Chrome latest

There's a host of small problems here. Your if statement, as is, will never reach the width compares. First of all, with the width being in a if else with the height, then height is always evaluated first and width is never hit if height is adjusted.
Next, your "current height|width" as seen at var windowH = $(window).height(); is never reset. This means, if the user show up with a viewport (say browser is minimized) of 200:150, then height:width will always be measured based on 200:150. This would make for a very different experience from someone using a much larger viewport.
Another issue, often found with window re-sizing, is the multiple amount of times your code will fire. This can cause major issue with overlapping commands, thus causing double feedback.
Below is how I would handle this and a suggested rebuild.
/* simple method to get the current window size as an object where h=height && w=width */
function getWindowSize() {
return { h: $(window).height(), w: $(window).width() };
}
function doWork(typ, msg) {
// report msg of change to console
console.log(typ == 'h' ? 'HEIGHT:\t' : 'WIDTH:\t', msg);
// we really only need fire your method if height has changed
if (typ == 'h') marginTop();
// a change was made, now to reset
window.sizeCheck = getWindowSize();
}
// your original method
// brokered off so it can be used independently
function marginTop() {
var currentH = $(window).height();
console.log('currentH', currentH)
$("#page").css("margin-top", currentH +'px');
$("#image-gallery, #page").height(currentH);
console.log('mTop fired!');
}
/* action area for window resize event */
function windowResize() {
// made my variables short and sweet,
// sch=sizeCheck, scu=sizeCurrent
var sch = window.sizeCheck, // get previously set size
scu = getWindowSize(),
maxH = sch.h + 90,
minH = sch.h - 90,
maxW = sch.w + 60,
minW = sch.w - 60;
if (scu.h > maxH) doWork('h', 'View Got <b>Taller</b>');
else if (scu.h < minH) doWork('h', 'View Got <i>shorteR</i>');
// for what you want, the following isn't even really nec
// but i'll leave it in so you can see the work
if (scu.w > maxW) doWork('w', 'View Got <b>Wider</b>');
else if (scu.w < minW) doWork('w', 'View Got <i>thinneR</i>');
}
$(function() {
// ezier to maintain one global variable than to scope
// shot 2 which could easily be overriden in a latter method,
// by simple confusion
window.sizeCheck = getWindowSize();
// call of event to establish correct margin for the page div
marginTop()
$(window).resize(function(e) {
// this will clear our timer everytime resize is called
if (this.tmrResize) clearTimeout(this.tmrResize);
// resize is called multiple times per second,
// this helps to seperate the call,
// and ensure a little time gap (1/4 second here)
this.tmrResize = setTimeout(windowResize, 250);
});
})
html, body { margin: 0; padding: 0; }
#image-gallery {
background: blue;
color: white;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
#page { background: white; color: red; height: 400px; position: relative; z-index: 1; }
p { padding: 3em; text-align: center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image-gallery">
<p>
image Gallery
</p>
</div>
<div id="page">
<p>
next page
</p>
</div>

Someone passed by and then voted -1 to my question. I'd just like to know who's the braveheart that judges others without even posting a simple comment. This behaviour should be forbidden, we're not on 9gag neither 4chan.

Related

detect screen size on iPhone match to IOS 14 and above [duplicate]

How can I get windowWidth, windowHeight, pageWidth, pageHeight, screenWidth, screenHeight, pageX, pageY, screenX, screenY which will work in all major browsers?
You can get the size of the window or document with jQuery:
// Size of browser viewport.
$(window).height();
$(window).width();
// Size of HTML document (same as pageHeight/pageWidth in screenshot).
$(document).height();
$(document).width();
For screen size you can use the screen object:
window.screen.height;
window.screen.width;
This has everything you need to know: Get viewport/window size
but in short:
var win = window,
doc = document,
docElem = doc.documentElement,
body = doc.getElementsByTagName('body')[0],
x = win.innerWidth || docElem.clientWidth || body.clientWidth,
y = win.innerHeight|| docElem.clientHeight|| body.clientHeight;
alert(x + ' × ' + y);
Fiddle
Please stop editing this answer. It's been edited 22 times now by different people to match their code format preference. It's also been pointed out that this isn't required if you only want to target modern browsers - if so you only need the following:
const width = window.innerWidth || document.documentElement.clientWidth ||
document.body.clientWidth;
const height = window.innerHeight|| document.documentElement.clientHeight||
document.body.clientHeight;
console.log(width, height);
Here is a cross browser solution with pure JavaScript (Source):
var width = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var height = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
A non-jQuery way to get the available screen dimension. window.screen.width/height has already been put up, but for responsive webdesign and completeness sake I think its worth to mention those attributes:
alert(window.screen.availWidth);
alert(window.screen.availHeight);
http://www.quirksmode.org/dom/w3c_cssom.html#t10 :
availWidth and availHeight - The available width and height on the
screen (excluding OS taskbars and such).
But when we talk about responsive screens and if we want to handle it using jQuery for some reason,
window.innerWidth, window.innerHeight
gives the correct measurement. Even it removes the scroll-bar's extra space and we don't need to worry about adjusting that space :)
Full 2020
I am surprised that question have about 10 years and it looks like so far nobody has given a full answer (with 10 values) yet. So I carefully analyse OP question (especially picture) and have some remarks
center of coordinate system (0,0) is in the viewport (browser window without bars and main borders) top left corner and axes are directed to right and down (what was marked on OP picture) so the values of pageX, pageY, screenX, screenY must be negative (or zero if page is small or not scrolled)
for screenHeight/Width OP wants to count screen height/width including system menu bar (eg. in MacOs) - this is why we NOT use .availWidth/Height (which not count it)
for windowWidth/Height OP don't want to count size of scroll bars so we use .clientWidth/Height
the screenY - in below solution we add to position of top left browser corner (window.screenY) the height of its menu/tabls/url bar). But it is difficult to calculate that value if download-bottom bar appears in browser and/or if developer console is open on page bottom - in that case this value will be increased of size of that bar/console height in below solution. Probably it is impossible to read value of bar/console height to make correction (without some trick like asking user to close that bar/console before measurements...)
pageWidth - in case when pageWidth is smaller than windowWidth we need to manually calculate size of <body> children elements to get this value (we do example calculation in contentWidth in below solution - but in general this can be difficult for that case)
for simplicity I assume that <body> margin=0 - if not then you should consider this values when calculate pageWidth/Height and pageX/Y
function sizes() {
const contentWidth = [...document.body.children].reduce(
(a, el) => Math.max(a, el.getBoundingClientRect().right), 0)
- document.body.getBoundingClientRect().x;
return {
windowWidth: document.documentElement.clientWidth,
windowHeight: document.documentElement.clientHeight,
pageWidth: Math.min(document.body.scrollWidth, contentWidth),
pageHeight: document.body.scrollHeight,
screenWidth: window.screen.width,
screenHeight: window.screen.height,
pageX: document.body.getBoundingClientRect().x,
pageY: document.body.getBoundingClientRect().y,
screenX: -window.screenX,
screenY: -window.screenY - (window.outerHeight-window.innerHeight),
}
}
// TEST
function show() {
console.log(sizes());
}
body { margin: 0 }
.box { width: 3000px; height: 4000px; background: red; }
<div class="box">
CAUTION: stackoverflow snippet gives wrong values for screenX-Y,
but if you copy this code to your page directly the values will be right<br>
<button onclick="show()" style="">CALC</button>
</div>
I test it on Chrome 83.0, Safari 13.1, Firefox 77.0 and Edge 83.0 on MacOs High Sierra
Graphical answer:
(............)
function wndsize(){
var w = 0;var h = 0;
//IE
if(!window.innerWidth){
if(!(document.documentElement.clientWidth == 0)){
//strict mode
w = document.documentElement.clientWidth;h = document.documentElement.clientHeight;
} else{
//quirks mode
w = document.body.clientWidth;h = document.body.clientHeight;
}
} else {
//w3c
w = window.innerWidth;h = window.innerHeight;
}
return {width:w,height:h};
}
function wndcent(){
var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
var _x = 0;var _y = 0;var offsetX = 0;var offsetY = 0;
//IE
if(!window.pageYOffset){
//strict mode
if(!(document.documentElement.scrollTop == 0)){offsetY = document.documentElement.scrollTop;offsetX = document.documentElement.scrollLeft;}
//quirks mode
else{offsetY = document.body.scrollTop;offsetX = document.body.scrollLeft;}}
//w3c
else{offsetX = window.pageXOffset;offsetY = window.pageYOffset;}_x = ((wndsize().width-hWnd.width)/2)+offsetX;_y = ((wndsize().height-hWnd.height)/2)+offsetY;
return{x:_x,y:_y};
}
var center = wndcent({width:350,height:350});
document.write(center.x+';<br>');
document.write(center.y+';<br>');
document.write('<DIV align="center" id="rich_ad" style="Z-INDEX: 10; left:'+center.x+'px;WIDTH: 350px; POSITION: absolute; TOP: '+center.y+'px; HEIGHT: 350px"><!--К сожалению, у Вас не установлен flash плеер.--></div>');
You can also get the WINDOW width and height, avoiding browser toolbars and other stuff. It is the real usable area in browser's window.
To do this, use:
window.innerWidth and window.innerHeight properties (see doc at w3schools).
In most cases it will be the best way, in example, to display a perfectly centred floating modal dialog. It allows you to calculate positions on window, no matter which resolution orientation or window size is using the browser.
To check height and width of your current loaded page of any website using "console" or after clicking "Inspect".
step 1: Click the right button of mouse and click on 'Inspect' and then click 'console'
step 2: Make sure that your browser screen should be not in 'maximize' mode. If the browser screen is in 'maximize' mode, you need to first click the maximize button (present either at right or left top corner) and un-maximize it.
step 3: Now, write the following after the greater than sign ('>') i.e.
> window.innerWidth
output : your present window width in px (say 749)
> window.innerHeight
output : your present window height in px (say 359)
Complete guide related to Screen sizes
JavaScript
For height:
document.body.clientHeight // Inner height of the HTML document body, including padding
// but not the horizontal scrollbar height, border, or margin
screen.height // Device screen height (i.e. all physically visible stuff)
screen.availHeight // Device screen height minus the operating system taskbar (if present)
window.innerHeight // The current document's viewport height, minus taskbars, etc.
window.outerHeight // Height the current window visibly takes up on screen
// (including taskbars, menus, etc.)
Note: When the window is maximized this will equal screen.availHeight
For width:
document.body.clientWidth // Full width of the HTML page as coded, minus the vertical scroll bar
screen.width // Device screen width (i.e. all physically visible stuff)
screen.availWidth // Device screen width, minus the operating system taskbar (if present)
window.innerWidth // The browser viewport width (including vertical scroll bar, includes padding but not border or margin)
window.outerWidth // The outer window width (including vertical scroll bar,
// toolbars, etc., includes padding and border but not margin)
Jquery
For height:
$(document).height() // Full height of the HTML page, including content you have to
// scroll to see
$(window).height() // The current document's viewport height, minus taskbars, etc.
$(window).innerHeight() // The current document's viewport height, minus taskbars, etc.
$(window).outerHeight() // The current document's viewport height, minus taskbars, etc.
For width:
$(document).width() // The browser viewport width, minus the vertical scroll bar
$(window).width() // The browser viewport width (minus the vertical scroll bar)
$(window).innerWidth() // The browser viewport width (minus the vertical scroll bar)
$(window).outerWidth() // The browser viewport width (minus the vertical scroll bar)
Reference: https://help.optimizely.com/Build_Campaigns_and_Experiments/Use_screen_measurements_to_design_for_responsive_breakpoints
With the introduction of globalThis in ES2020 you can use properties like.
For screen size:
globalThis.screen.availWidth
globalThis.screen.availHeight
For Window Size
globalThis.outerWidth
globalThis.outerHeight
For Offset:
globalThis.pageXOffset
globalThis.pageYOffset
...& so on.
alert("Screen Width: "+ globalThis.screen.availWidth +"\nScreen Height: "+ globalThis.screen.availHeight)
If you need a truly bulletproof solution for the document width and height (the pageWidth and pageHeight in the picture), you might want to consider using a plugin of mine, jQuery.documentSize.
It has just one purpose: to always return the correct document size, even in scenarios when jQuery and other methods fail. Despite its name, you don't necessarily have to use jQuery – it is written in vanilla Javascript and works without jQuery, too.
Usage:
var w = $.documentWidth(),
h = $.documentHeight();
for the global document. For other documents, e.g. in an embedded iframe you have access to, pass the document as a parameter:
var w = $.documentWidth( myIframe.contentDocument ),
h = $.documentHeight( myIframe.contentDocument );
Update: now for window dimensions, too
Ever since version 1.1.0, jQuery.documentSize also handles window dimensions.
That is necessary because
$( window ).height() is buggy in iOS, to the point of being useless
$( window ).width() and $( window ).height() are unreliable on mobile because they don't handle the effects of mobile zooming.
jQuery.documentSize provides $.windowWidth() and $.windowHeight(), which solve these issues. For more, please check out the documentation.
I wrote a small javascript bookmarklet you can use to display the size. You can easily add it to your browser and whenever you click it you will see the size in the right corner of your browser window.
Here you find information how to use a bookmarklet
https://en.wikipedia.org/wiki/Bookmarklet
Bookmarklet
javascript:(function(){!function(){var i,n,e;return n=function(){var n,e,t;return t="background-color:azure; padding:1rem; position:fixed; right: 0; z-index:9999; font-size: 1.2rem;",n=i('<div style="'+t+'"></div>'),e=function(){return'<p style="margin:0;">width: '+i(window).width()+" height: "+i(window).height()+"</p>"},n.html(e()),i("body").prepend(n),i(window).resize(function(){n.html(e())})},(i=window.jQuery)?(i=window.jQuery,n()):(e=document.createElement("script"),e.src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js",e.onload=n,document.body.appendChild(e))}()}).call(this);
Original Code
The original code is in coffee:
(->
addWindowSize = ()->
style = 'background-color:azure; padding:1rem; position:fixed; right: 0; z-index:9999; font-size: 1.2rem;'
$windowSize = $('<div style="' + style + '"></div>')
getWindowSize = ->
'<p style="margin:0;">width: ' + $(window).width() + ' height: ' + $(window).height() + '</p>'
$windowSize.html getWindowSize()
$('body').prepend $windowSize
$(window).resize ->
$windowSize.html getWindowSize()
return
if !($ = window.jQuery)
# typeof jQuery=='undefined' works too
script = document.createElement('script')
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'
script.onload = addWindowSize
document.body.appendChild script
else
$ = window.jQuery
addWindowSize()
)()
Basically the code is prepending a small div which updates when you resize your window.
In some cases related with responsive layout $(document).height() can return wrong data that displays view port height only.
For example when some div#wrapper has height:100%, that #wrapper can be stretched by some block inside it. But it's height still will be like viewport height. In such situation you might use
$('#wrapper').get(0).scrollHeight
That represents actual size of wrapper.
I developed a library for knowing the real viewport size for desktops and mobiles browsers, because viewport sizes are inconsistents across devices and cannot rely on all the answers of that post (according to all the research I made about this) : https://github.com/pyrsmk/W
Sometimes you need to see the width/height changes while resizing the window and inner content.
For that I've written a little script that adds a log box that dynamicly monitors all the resizing and almost immediatly updates.
It adds a valid HTML with fixed position and high z-index, but is small enough, so you can:
use it on an actual site
use it for testing mobile/responsive
views
Tested on: Chrome 40, IE11, but it is highly possible to work on other/older browsers too ... :)
function gebID(id){ return document.getElementById(id); }
function gebTN(tagName, parentEl){
if( typeof parentEl == "undefined" ) var parentEl = document;
return parentEl.getElementsByTagName(tagName);
}
function setStyleToTags(parentEl, tagName, styleString){
var tags = gebTN(tagName, parentEl);
for( var i = 0; i<tags.length; i++ ) tags[i].setAttribute('style', styleString);
}
function testSizes(){
gebID( 'screen.Width' ).innerHTML = screen.width;
gebID( 'screen.Height' ).innerHTML = screen.height;
gebID( 'window.Width' ).innerHTML = window.innerWidth;
gebID( 'window.Height' ).innerHTML = window.innerHeight;
gebID( 'documentElement.Width' ).innerHTML = document.documentElement.clientWidth;
gebID( 'documentElement.Height' ).innerHTML = document.documentElement.clientHeight;
gebID( 'body.Width' ).innerHTML = gebTN("body")[0].clientWidth;
gebID( 'body.Height' ).innerHTML = gebTN("body")[0].clientHeight;
}
var table = document.createElement('table');
table.innerHTML =
"<tr><th>SOURCE</th><th>WIDTH</th><th>x</th><th>HEIGHT</th></tr>"
+"<tr><td>screen</td><td id='screen.Width' /><td>x</td><td id='screen.Height' /></tr>"
+"<tr><td>window</td><td id='window.Width' /><td>x</td><td id='window.Height' /></tr>"
+"<tr><td>document<br>.documentElement</td><td id='documentElement.Width' /><td>x</td><td id='documentElement.Height' /></tr>"
+"<tr><td>document.body</td><td id='body.Width' /><td>x</td><td id='body.Height' /></tr>"
;
gebTN("body")[0].appendChild( table );
table.setAttribute(
'style',
"border: 2px solid black !important; position: fixed !important;"
+"left: 50% !important; top: 0px !important; padding:10px !important;"
+"width: 150px !important; font-size:18px; !important"
+"white-space: pre !important; font-family: monospace !important;"
+"z-index: 9999 !important;background: white !important;"
);
setStyleToTags(table, "td", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");
setStyleToTags(table, "th", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");
table.style.setProperty( 'margin-left', '-'+( table.clientWidth / 2 )+'px' );
setInterval( testSizes, 200 );
EDIT: Now styles are applied only to logger table element - not to all tables - also this is a jQuery-free solution :)
You can use the Screen object to get this.
The following is an example of what it would return:
Screen {
availWidth: 1920,
availHeight: 1040,
width: 1920,
height: 1080,
colorDepth: 24,
pixelDepth: 24,
top: 414,
left: 1920,
availTop: 414,
availLeft: 1920
}
To get your screenWidth variable, just use screen.width, same with screenHeight, you would just use screen.height.
To get your window width and height, it would be screen.availWidth or screen.availHeight respectively.
For the pageX and pageY variables, use window.screenX or Y. Note that this is from the VERY LEFT/TOP OF YOUR LEFT/TOP-est SCREEN. So if you have two screens of width 1920 then a window 500px from the left of the right screen would have an X value of 2420 (1920+500). screen.width/height, however, display the CURRENT screen's width or height.
To get the width and height of your page, use jQuery's $(window).height() or $(window).width().
Again using jQuery, use $("html").offset().top and $("html").offset().left for your pageX and pageY values.
here is my solution!
// innerWidth
const screen_viewport_inner = () => {
let w = window,
i = `inner`;
if (!(`innerWidth` in window)) {
i = `client`;
w = document.documentElement || document.body;
}
return {
width: w[`${i}Width`],
height: w[`${i}Height`]
}
};
// outerWidth
const screen_viewport_outer = () => {
let w = window,
o = `outer`;
if (!(`outerWidth` in window)) {
o = `client`;
w = document.documentElement || document.body;
}
return {
width: w[`${o}Width`],
height: w[`${o}Height`]
}
};
// style
const console_color = `
color: rgba(0,255,0,0.7);
font-size: 1.5rem;
border: 1px solid red;
`;
// testing
const test = () => {
let i_obj = screen_viewport_inner();
console.log(`%c screen_viewport_inner = \n`, console_color, JSON.stringify(i_obj, null, 4));
let o_obj = screen_viewport_outer();
console.log(`%c screen_viewport_outer = \n`, console_color, JSON.stringify(o_obj, null, 4));
};
// IIFE
(() => {
test();
})();
This how I managed to get the screen width in React JS Project:
If width is equal to 1680 then return 570 else return 200
var screenWidth = window.screen.availWidth;
<Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a </Label>
Screen.availWidth

Show a series of images on scroll

The closest solution I found is Show div on scrollDown after 800px.
I'm learning HTML, CSS, and JS, and I decided to try to make a digital flipbook: a simple animation that would play (ie, load frame after frame) on the user's scroll.
I figured I would add all the images to the HTML and then use CSS to "stack them" in the same position, then use JS or jQuery to fade one into the next at different points in the scroll (ie, increasing pixel distances from the top of the page).
Unfortunately, I can't produce the behavior I'm looking for.
HTML (just all the frames of the animation):
<img class="frame" id="frame0" src="images/hand.jpg">
<img class="frame" id="frame1" src="images/frame_0_delay-0.13s.gif">
CSS:
body {
height: 10000px;
}
.frame {
display: block;
position: fixed;
top: 0px;
z-index: 1;
transition: all 1s;
}
#hand0 {
padding: 55px 155px 55px 155px;
background-color: white;
}
.frameHide {
opacity: 0;
left: -100%;
}
.frameShow {
opacity: 1;
left: 0;
}
JS:
frame0 = document.getElementById("frame0");
var myScrollFunc = function() {
var y = window.scrollY;
if (y >= 800) {
frame0.className = "frameShow"
} else {
frame0.className = "frameHide"
}
};
window.addEventListener("scroll", myScrollFunc);
};
One of your bigger problems is that setting frame0.className = "frameShow" removes your initial class frame, which will remove a bunch of properties. To fix this, at least in a simple way, we can do frame0.className = "frame frameShow", etc. Another issue is that frame0 is rendered behind frame1, which could be fixed a variety of ways. ie. Putting frame0's <img> after frame1, or setting frame0's CSS to have a z-index:2;, and then setting frame0's class to class="frame frameHide" so it doesn't show up to begin with. I also removed the margin and padding from the body using CSS, as it disturbs the location of the images. I have made your code work the way I understand you wanted it to, here is a JSFiddle.
It depends on your case, for example, in this jsFiddle 1 I'm showing the next (or previous) frame depending on the value of the vertical scroll full window.
So for my case the code is:
var jQ = $.noConflict(),
frames = jQ('.frame'),
win = jQ(window),
// this is very important to be calculated correctly in order to get it work right
// the idea here is to calculate the available amount of scrolling space until the
// scrollbar hits the bottom of the window, and then divide it by number of frames
steps = Math.floor((jQ(document).height() - win.height()) / frames.length),
// start the index by 1 since the first frame is already shown
index = 1;
win.on('scroll', function() {
// on scroll, if the scroll value equal or more than a certain number, fade the
// corresponding frame in, then increase index by one.
if (win.scrollTop() >= index * steps) {
jQ(frames[index]).animate({'opacity': 1}, 50);
index++;
} else {
// else if it's less, hide the relative frame then decrease the index by one
// thus it will work whether the user scrolls up or down
jQ(frames[index]).animate({'opacity': 0}, 50);
index--;
}
});
Update:
Considering another scenario, where we have the frames inside a scroll-able div, then we wrap the .frame images within another div .inner.
jsFiddle 2
var jQ = $.noConflict(),
cont = jQ('#frames-container'),
inner = jQ('#inner-div'),
frames = jQ('.frame'),
frameHeight = jQ('#frame1').height(),
frameWidth = jQ('#frame1').width() + 20, // we add 20px because of the horizontal scroll
index = 0;
// set the height of the outer container div to be same as 1 frame height
// and the inner div height to be the sum of all frames height, also we
// add some pixels just for safety, 20px here
cont.css({'height': frameHeight, 'width': frameWidth});
inner.css({'height': frameHeight * frames.length + 20});
cont.on('scroll', function() {
var space = index * frameHeight;
if (cont.scrollTop() >= space) {
jQ(frames[index]).animate({'opacity': 1}, 0);
index++;
} else {
jQ(frames[index]).animate({'opacity': 0}, 0);
index--;
}
});
** Please Note that in both cases all frames must have same height.

jQuery scroll event: how to determine amount scrolled (scroll delta) in pixels?

I have this event:
$(window).scroll(function(e){
console.log(e);
})
I want to know, how much I have scroll value in pixels, because I think, scroll value depends from window size and screen resolution.
Function parameter e does not contains this information.
I can store $(window).scrollTop() after every scroll and calculate difference, but can I do it differently?
The "scroll value" does not depend on the window size or screen resolution. The "scroll value" is simply the number of pixels scrolled.
However, whether you are able to scroll at all, and the amount you can scroll is based on available real estate for the container and the dimensions of the content within the container (in this case the container is document.documentElement, or document.body for older browsers).
You are correct that the scroll event does not contain this information. It does not provide a delta property to indicate the number of pixels scrolled. This is true for the native scroll event and the jQuery scroll event. This seems like it would be a useful feature to have, similar to how mousewheel events provide properties for X and Y delta.
I do not know, and will not speculate upon, why the powers-that-be did not provide a delta property for scroll, but that is out of scope for this question (feel free to post a separate question about this).
The method you are using of storing scrollTop in a variable and comparing it to the current scrollTop is the best (and only) method I have found. However, you can simplify this a bit by extending jQuery to provide a new custom event, per this article: http://learn.jquery.com/events/event-extensions/
Here is an example extension I created that works with window / document scrolling. It is a custom event called scrolldelta that automatically tracks the X and Y delta (as scrollLeftDelta and scrollTopDelta, respectively). I have not tried it with other elements; leaving this as exercise for the reader. This works in currrent versions of Chrome and Firefox. It uses the trick for getting the sum of document.documentElement.scrollTop and document.body.scrollTop to handle the bug where Chrome updates body.scrollTop instead of documentElement.scrollTop (IE and FF update documentElement.scrollTop; see https://code.google.com/p/chromium/issues/detail?id=2891).
JSFiddle demo: http://jsfiddle.net/tew9zxc1/
Runnable Snippet (scroll down and click Run code snippet):
// custom 'scrolldelta' event extends 'scroll' event
jQuery.event.special.scrolldelta = {
delegateType: "scroll",
bindType: "scroll",
handle: function (event) {
var handleObj = event.handleObj;
var targetData = jQuery.data(event.target);
var ret = null;
var elem = event.target;
var isDoc = elem === document;
var oldTop = targetData.top || 0;
var oldLeft = targetData.left || 0;
targetData.top = isDoc ? elem.documentElement.scrollTop + elem.body.scrollTop : elem.scrollTop;
targetData.left = isDoc ? elem.documentElement.scrollLeft + elem.body.scrollLeft : elem.scrollLeft;
event.scrollTopDelta = targetData.top - oldTop;
event.scrollTop = targetData.top;
event.scrollLeftDelta = targetData.left - oldLeft;
event.scrollLeft = targetData.left;
event.type = handleObj.origType;
ret = handleObj.handler.apply(this, arguments);
event.type = handleObj.type;
return ret;
}
};
// bind to custom 'scrolldelta' event
$(window).on('scrolldelta', function (e) {
var top = e.scrollTop;
var topDelta = e.scrollTopDelta;
var left = e.scrollLeft;
var leftDelta = e.scrollLeftDelta;
// do stuff with the above info; for now just display it to user
var feedbackText = 'scrollTop: ' + top.toString() + 'px (' + (topDelta >= 0 ? '+' : '') + topDelta.toString() + 'px), scrollLeft: ' + left.toString() + 'px (' + (leftDelta >= 0 ? '+' : '') + leftDelta.toString() + 'px)';
document.getElementById('feedback').innerHTML = feedbackText;
});
#content {
/* make window tall enough for vertical scroll */
height: 2000px;
/* make window wide enough for horizontal scroll */
width: 2000px;
/* visualization of scrollable content */
background-color: blue;
}
#feedback {
border:2px solid red;
padding: 4px;
color: black;
position: fixed;
top: 0;
height: 20px;
background-color: #fff;
font-family:'Segoe UI', 'Arial';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='feedback'>scrollTop: 0px, scrollLeft: 0px</div>
<div id='content'></div>
Note that you may want debounce the event depending on what you are doing. You didn't provide very much context in your question, but if you give a better example of what you are actually using this info for we can provide a better answer. (Please show more of your code, and how you are using the "scroll value").
To detemine how many pixels were scrolled you have to keep in mind that the scroll event gets fired almost every pixel that you move. The way to accomplish it is to save the previous scrolled value and compare that in a timeout. Like this:
var scrollValue = 0;
var scrollTimeout = false
$(window).scroll(function(event){
/* Clear it so the function only triggers when scroll events have stopped firing*/
clearTimeout(scrollTimeout);
/* Set it so it fires after a second, but gets cleared after a new triggered event*/
scrollTimeout = setTimeout(function(){
var scrolled = $(document).scrollTop() - scrollValue;
scrollValue = $(document).scrollTop();
alert("The value scrolled was " + scrolled);
}, 1000);
});
This way you will get the amount of scrolled a second after scrolling (this is adjustable but you have to keep in mind that the smooth scrolling that is so prevalent today has some run-out time and you dont want to trigger before a full stop).
The other way to do this? Yes, possible, with jQuery Mobile
I do not appreciate this solution, because it is necessary to include heavy jQuery mobile. Solution:
var diff, top = 0;
$(document).on("scrollstart",function () {
// event fired when scrolling is started
top = $(window).scrollTop();
});
$(document).on("scrollstop",function () {
// event fired when scrolling is stopped
diff = Math.abs($(window).scrollTop() - top);
});
To reduce the used processing power by adding a timer to a Jquery scroll method is probably not a great idea. The visual effect is indeed quite bad.
The whole web browsing experience could be made much better by hiding the scrolling element just when the scroll begins and making it slide in (at the right position) some time after. The scrolling even can be checked with a delay too.
This solution works great.
$(document).ready(function() {
var element = $('.movable_div'),
originalY = element.offset().top;
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
element.hide();
element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + 35
}, 2000,function(){element.slideDown(500,"swing");});
});
});
Live demo here

Changing the background image according to resolution - javascript only

there's a lot of this question scattered over stackoverflow, but I can't seem to find an answer that specifically suits my situation.
I have made a background in HD 1920x1080 for a school project I'm making, and I'm trying to make it fit for every resolution there is. So what I did was resizing this image for every specific resolution, putting me in an awkward spot to code it, as I cannot use jQuery, I'm not allowed to.
I'm thinking of using the screen.width property, but I'd need a length too as I have multiple backgrounds with the ...x768 resoulution.
Is there anyone who'd be able to tell me how to change my body's background, depending on the user's height and width of the screen?
Thank you very much,
Michiel
You can use window.innerWidth and window.innerHeight to get the current dimensions of your browser's window.
Which means that if your browser takes half of your 1920x1080 desktop, it'll compute to something like:
window.innerWidth ~= 540
window.innerHeight ~= 1920 // actually something smaller because it doesn't count your browser's chrome
Your window can of course change size, and if you want to handle that, you can listen to the event "resize" for your window:
window.addEventListener('resize', function () {
// change background
});
To change the body's background without jQuery, you can do something like this:
document.body.style.backgroundImage = "url(/* url to your image...*/)";
To recap:
// when the window changes size
window.addEventListener('resize', function () {
var windowWidth = window.innerWidth; // get the new window width
var windowHeight = window.innerHeight; // get the new window height
// use windowWidth and windowHeight here to decide what image to put as a background image
var backgroundImageUrl = ...;
// set the new background image
document.body.style.backgroundImage = "url(" + backgroundImageUrl + ")";
});
I am not sure what browsers you are supposed to be compatible with. This should work in all latest versions of the big browsers.
You may check the window width and change the background depending on the results.
var width = window.innerWidth;
var height = window.innerHeight;
var body = document.body;
if (width <= 1600 && height <= 1000) {
body.style.background = "url(path/to/1600x1000.jpg)";
}
if (width <= 1400 && height <= 900) {
body.style.background = "url(path/to/1400x900.jpg)";
}
// continue as desired
http://jsbin.com/wosaduho/1/
Even better, use some media queries to reduce javascript required.
#media screen and (max-width: 1600px) {
.element {
background: url(path/to/1600x1000.jpg);
}
}
#media screen and (max-width: 1400px) {
.element {
background: url(path/to/1400x900.jpg);
}
}
body {
background-image: url(images/background.jpg);
background-size:cover;/*If you put "contain" it will preserve its intrinsic aspect ratio*/ background-repeat: no-repeat;
}
Try this
You might want to trigger a function like the following on window load and/or on window resize:
function SwapImage(){
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),
el = document.getElementById('change-my-background');
// use conditionals to decide which image to show
if(w < 1200 && h < 800){
el.style.backgroundImage = "url('img_1200x800.png')";
}
if(w < 900 && h < 600){
el.style.backgroundImage = "url('img_900x600.png')";
}
// etc...
}

Resizing an image using Javascript running in Opera Browser

I hope someone can help with this quirky issue I am having with the Opera Browser, I have version 11 Beta installed, but I suspect is a common problem in Opera.
The website and page in question is http://www.amigaos.net/index.html.
At the bottom of the body of the html I have the following code which resizes the 3 images you see on this webpage depending on width of the viewport at page load. In Safari and FireFox the code works fine, but in Opera the following lines which involve resizing the width and height of an image do not work:
document.getElementById('img1').width = '475';
document.getElementById('img1').height = '375';
Here is the code in full (sorry, about the layout, stackoverflow hasn't formatted carriage returns correctly)
<script type="text/javascript">
function GetWidth()
{
var x = 0;
if (typeof window.innerWidth != 'undefined')
{
x = window.innerWidth;
}
else if (document.documentElement && document.documentElement.clientHeight)
{
x = document.documentElement.clientWidth;
}
else if (document.body)
{
x = document.getElementsByTagName('body')[0].clientWidth;
}
return x;
}
width = GetWidth();
if (width>=1680)
{
document.getElementById('img1').width = '475';
document.getElementById('img1').height = '375';
document.getElementById('img2').width = '475';
document.getElementById('img2').height = '375';
document.getElementById('img3').width = '475';
document.getElementById('img3').height = '375';
}
else if ((width>800) && (width<=1280))
{
document.getElementById('img1').width = '300';
document.getElementById('img1').height = '235';
document.getElementById('img2').width = '300';
document.getElementById('img2').height = '235';
document.getElementById('img3').width = '300';
document.getElementById('img3').height = '235';
}
else if (width<=800)
{
document.getElementById('img1').width = '225';
document.getElementById('img1').height = '195';
document.getElementById('img2').width = '225';
document.getElementById('img2').height = '195';
document.getElementById('img3').width = '225';
document.getElementById('img3').height = '195';
}
</script>
instead of doing width and height attributes, I think you can just set width: 33% via CSS and have the scaling happen automatically, regardless of the browser window size. Better solution than trying to use javascript, IMHO.
Here's a simple tutorial: http://haslayout.net/css-tuts/CSS-Proportional-Image-Scale
you are making this way too complicated. I don't think your issue is browser-specific, you just need to recode your script.
First. I would recommmend using percentages.. Not sure how you will guess the visitors browser width in pixels.
Let's say that your three resizeable images are 20% width of your browser. So your css would be:
#img1, #img2, #img3 {
width: 20%;
}
now that your css says that your images are 20% of the total with, you're good to add some js. Keep in mind that the percentage will be that of its outer container.
<script type=text/javascript">
function resizeImages() {
document.getElementById('img1').style.height = (document.body.clientHeight - 100) * 0.2;
document.getElementById('img2').style.height = (document.body.clientHeight - 100) * 0.2;
document.getElementById('img3').style.height = (document.body.clientHeight - 100) * 0.2;
}
</script>
and most importantly.. call your function:
add this to your body tag:
<body onresize="resizeImages()">
boom.. you're done.

Categories

Resources