Show a series of images on scroll - javascript

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.

Related

Pinning Elements with Debounced Scroll Event for Performance

What is the right way to smoothly pin an element according to scroll position?
I tried debouncing a scroll listener for performance but the pinning is not accurate. Even with debouncing set to 10ms it's not smooth and the element doesn't snap cleanly to its initial position.
var scrolling = false;
var stickPosY = 100;
var heights = [];
$(".element").each( function(index) {
heights[index] = $(".element[data-trigger=" + index + "]").offset().top;
});
function pin() {
if ( !$("#aside").hasClass("fixed") ) {
var stickyLeft = $("#aside").offset().left;
var stickyWidth = $("#aside").outerWidth();
var stickyTop = $("#aside").offset().top - stickPosY;
$("#aside").addClass("fixed");
$("#aside").css({"left": stickyLeft, "top": stickyTop, "width": stickyWidth});
}
}
function unpin() {
$("#aside").css({"left": "", "top": "", "width": ""});
$("#aside").removeClass("fixed")
}
$( window ).scroll( function() {
scrolling = true;
});
setInterval( function() {
if ( scrolling ) {
scrolling = false;
var y = window.scrollY;
console.log(y);
// PIN SIDEBAR
y > stickPosY ? pin() : unpin();
//TRIGGERS
for (var i=0; i < heights.length; i++) {
if (y >= heights[i]) {
$('.element[data-trigger="' + i + '"]').addClass("blue");
}
else {
$('.element[data-trigger="' + i + '"]').removeClass("blue");
}
}
}
}, 250 );
Here's my Pen
I tried to use scrollMagic for the project on a scene with a pin and additional triggers but the scrolling wasn't very smooth. So I'm trying to rebuild it with a stripped-down version and debounced listeners. Is this approach possible, or should I rather try to optimize my scrollMagic scene?
As James points out, you can just use position: sticky as one option, but that doesn't work in older browsers and its uses are limited to simpler situations in newer browsers, so I'll continue with the JS solution assuming you want to go that route.
There is a lot going on in your JS, and I think you are probably overcomplicating things, so I will give you a few basics to consider.
When you are toggling things based on scroll, either toggle inline styles or a class, but not both. I would recommend toggling a class because it allows you to have one function that can work on multiple screen sizes (i.e., you can use media queries to change the behavior of your toggled class based on screen size). Also it keeps all your styles in one place instead of having them split between your JS and your stylesheet.
Try to keep the work you're doing while scrolling as minimal as possible. For example, cache references to elements in variables outside your scroll function so you're not continually looking them up every time you scroll a pixel. Avoid loops inside scroll functions.
Using setInterval is not generally the recommended approach for increasing performance on scroll functions. All that is going to do is run a function every X amount of time, all the time, whether you're scrolling or not. What you really want to do is rate-limit your scroll function directly. That way, if you scroll a long ways real fast your function will only be called a fraction of the total times it would otherwise be called, but if you scroll a short distance slowly it will still be called a minimum number of times to keep things looking smooth, and if you don't scroll at all then you're not calling your function at all. Also, you probably want to throttle your function in this case, not debounce it.
Consider using the throttle function from Underscore.js or Lodash.js instead of inventing your own because those ones are highly performant and guaranteed to work across a wide variety of browsers.
Here is a simple example of sticking an element to the top of the screen on scroll, throttled with Lodash. I'm using a 25ms throttle, which is about the maximum amount I'd recommend for keeping things looking smooth where you won't really notice the delay in the element sticking/unsticking as you scroll past your threshold. You could go down to as little as 10ms.
$(function() {
$(window).on('scroll', _.throttle(toggleClass, 25));
const myThing = $('#my-thing');
const threshold = $('#dummy-1').height();
function toggleClass() {
const y = window.scrollY;
if (y > threshold) {
myThing.addClass('stuck')
} else {
myThing.removeClass('stuck');
}
}
});
#dummy-1 {
height: 150px;
background-color: steelblue;
}
#dummy-2 {
height: 150px;
background-color: gold;
}
#my-thing {
width: 300px;
height: 75px;
background-color: firebrick;
position: absolute;
top: 150px;
left: 0;
}
#my-thing.stuck {
position: fixed;
top: 0;
}
body {
margin: 0;
height: 2000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.0/lodash.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dummy-1"></div>
<div id="dummy-2"></div>
<div id="my-thing"></div>
You could try fixed or sticky CSS positioning:
#element {
position: fixed;
top: 80px;
left: 10px;
}
Position: fixed would keep the element always at 80px from the top and 10px from the left edge regardless of scroll position.
#element{
position: sticky;
top: 0;
right: 0;
left: 0;
}
This is from a project of mine. The element is a nav bar. It sits below a header bar, so when you are at the top of the page, you see the header then the nav below it, and as you scroll down, the header moves off screen but the nav sticks at the top and is always visible.

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

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.

Loop with trigger (which contains animation) not working

So I seem to have run into a bit of a dead end. I'm making a page which has an image slider. The slider has three images, one centered on the screen, the other two overflow on the left and right. When you click on the button to advance the slides it runs this code....
$('#slideRight').click(function() {
if ($('.container').is(':animated')) {return false;}
var next=parseInt($('.container img:last-of-type').attr('id')) + 1;
if (next == 12) {
next = 0;
}
var diff = galsize() - 700;
if ($('.thumbs').css("left") == "0px") {
var plus = 78;
} else {
var plus = 0;
}
var app='<img id="' + next + '" src="' + imgs[next].src + '">';
$('.container').width('2800px').append(app);
$('.container').animate({marginLeft: (diff + plus) + "px"}, 300, function() {
$('.container img:first-of-type').remove();
$('.container').width('2100px').css("margin-left", (galsize() + plus) + "px");
});
}); // end right click
This works just fine, not a problem..... I also have an interval set up to run this automatically every 5 seconds to form a slideshow...
var slideShow = setInterval(function() {
$('#slideRight').trigger("click");
}, 5000);
This also works perfectly, not a problem.... However my problem is this.... I have thumbnails, when you click on a thumbnail, it should run this code until the current picture is the same as the thumbnail.... here is the code....
$('img.thumbnail').click(function() {
clearInterval(slideShow);
var src = $(this).attr("src");
while ($('.container img:eq(1)').attr('src') != src) {
$('#slideRight').trigger("click");
}
});
When I click on the thumbnail nothing happens... I've used alert statements to try and debug, what ends up happening is this....
The while loop executes, however nothing happens the first time. The slide is not advanced at all. Starting with the second execution, the is('::animated') is triggered EVERY TIME and the remainder of the slideRight event is not executed...
So my first problem, can anyone shed some light on why it doesn't run the first time?
And my second question, is there any way to wait until the animation is complete before continuing with the loop?
Any help would be appreciated. Thank you!
I'm going to start with the second part of your question, regarding completing the animation before continuing with the loop.
I have done something similar in the past, and what I did was set two global variables to control the animation. One variable is for how long you want the period to be, the other is a counter for how much time since the last loop.
So, for example:
$timeToChange = 5; // in Seconds
$timeSinceReset = 0; // also in Seconds
Set your interval for one second and call a new function (autoAdvance()):
var slideShow = setInterval(function() {
autoAdvance();
}, 1000); // only one second
and then use the counter variable to count each time the interval is called (each second). Something like:
function autoAdvance(){
if($timeSinceReset == $timeToChange){
$timeSinceReset = 0;
$('#slideRight').trigger("click"); // execute click if satisfied
}
else{$timeSinceReset++;}
}
To stop from looping until the animation is done, reset $timeSinceReset back to 0 (zero) when you click on the thumbnail. Something like:
$('#thumbnail').click(function(){
$timeSinceReset = 0;
});
That'll give you a nice 5 second buffer (or whatever you set $timeToChange) before the loop continues.
As for the first part of your question, grab the number of the particular thumbnail, and use that to scroll to the appropriate image. Something like:
$('.thumb').click(function (each) {
$childNumber = $(this).index();
});
which you cansee in this fiddle. Click in one of the grey boxes and it'll tell you which one you clicked in. Use that info to scroll to the appropriate image (1, 2 or 3 if you only have three images).
Hope this helps.
Here is a full solution for one possible way of doing it at this fiddle.
HTML:
The top container holds the images. In this particular example I've included three, using divs instead of images. Whether you use images or divs doesn't change anything.
<div class="holder_container">
<div class="img_container">
<div class="photo type1">ONE</div>
<div class="photo type2">TWO</div>
<div class="photo type3">THREE</div>
</div>
</div>
.img_container holds all the images, and is the same width as the sum of the widths of the images. In this case, each image (.photo) is 150px wide and 50px tall, so .img_container is 450px wide and 50px tall. .holder_container is the same dimensions as a single image. When this runs, the .holder_container is set to hide any overflow while .img_container moves its position left or right.
Included also are two nav buttons (forward and back)
<div class="nav_buttons">
<div class="nav back"><<<</div>
<div class="nav forward">>>></div>
</div>
As well as three thumbnail images - one for each image in the top container
<div class="top">
<div class="thumb"></div>
<div class="thumb"></div>
<div class="thumb"></div>
</div>
CSS:
Refer to the JS Fiddle for all CSS rules.
The most important are:
.holder_container {
margin: 0px;
padding: 0px;
height: 50px;
width: 150px;
position: relative;
overflow: hidden;
}
.img_container {
margin: 0px;
padding: 0px;
height: 50px;
width: 450px;
position: relative;
left: 0px;
top: 0px;
}
In the example, .type1, .type2 and .type3 are only used to color the image divs so you can see the animation. They can be left out of your code.
JavaScript:
The javascript contains the following elements…
Variables:
var timeToChange = 3; // period of the image change, in seconds
var timeSinceReset = 0; // how many seconds have passed since last image change
var currentImage = 1; // Which image you are currently viewing
var totalImages = 3; // How many images there are in total
Functions:
autoAdvance - called once every second via setInterval. Counts the number of seconds since the last image change. If the number of seconds that has passed is equal to the period, a function is called that switches the images.
function autoAdvance() {
if (timeSinceReset == timeToChange) {
timeSinceReset = 0;
moveNext();
} else {
timeSinceReset++;
}
}
moveNext() - moves to the next image. If the current image is the last (currentImage == totalImages) then currentImages is set back to 1 and the first image is displayed.
function moveNext(){
if(currentImage == totalImages){
currentImage = 1;
var newPos = 0 + 'px';
$('.img_container').animate({left: newPos}, 300);
}else{
currentImage++;
var newPos = -((currentImage-1) * 150) + 'px'; // child numbers are zero-based
$('.img_container').animate({left: newPos}, 300);
}
}
Rest of code:
If one of the thumbs is clicked, move to the corresponding image.
$('.thumb').click(function (each) {
timeSinceReset = 0;
var childNumber = $(this).index();
currentImage = childNumber + 1; // child numbers are zero-based
var newPos = -(childNumber * 150) + 'px'; // child numbers are zero-based
$('.img_container').animate({left: newPos}, 300);
});
If one of the navigation buttons is clicked, move accordingly. If "back" is clicked, move one image backwards (or to last image if currently on first). If "first" is clicked, move one image forwards (or to first image if currently on last).
$('.nav').click(function(){
timeSinceReset = 0;
if($(this).hasClass('back')){ // Back button
if(currentImage == 1){
currentImage = totalImages;
}else{
currentImage--;
}
}else{ // Forward button
if(currentImage == totalImages){
currentImage = 1;
}else{
currentImage++;
}
}
var newPos = -((currentImage-1) * 150) + 'px';
$('.img_container').animate({left: newPos}, 300);
});
Here is the link to the fiddle example.

Problems calculating the actual height of web page elements with Javascript and JQuery?

I am modifying some code I found for paginating HTML content into a div. The code is from the jQuery rain site found on this page:
http://www.jqueryrain.com/?HtS47Rzc
The intent of this code is to take a large chunk of HTML, scan the top level child elements, and create a page object for each group of child elements that fit within a desired height (E.g. 400px). Once all the pages are built, each page is wrapped in a new div. The problem I'm having is that the calculated pages aren't close to the desired height once rendered to the page. So instead of each page having a nice block of text that neatly bumps into but does not exceed the bottom of the containing div, some pages have text falling far short of the desired page bottom and some exceed the page bottom. Actually they no longer exceed the page bottom since I added code that scans the pages array after each page has been wrapped with a div and sets the container div to the maximum div height found.
One thought I had is that the wrapping of the div was causing the variance so I explicitly added CSS rules to set the margins and padding to 0px. That had no effect. Can anyone tell me how to adjust the code so that the page height calculations work properly?
UPDATE: I'm showing the CSS for the div that holds a page and the DIV that contains it.
.example{
background:#FFF;
width:410px;
border:1px #000 solid;
margin:20px auto;
padding:15px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px
}
The page divs all have the class of "page":
#content .page {
position:absolute;
margin: 0px 0px 0px 0px;
padding: 0px 0px 0px 0px;
top:0px;
}
Here is my Javascript modified code. Note, the object being processed by the function is the main div that shows the paginated content:
(function ($) {
$.fn.extend({
MyPagination: function (options) {
var defaults = {
height: 400,
fadeSpeed: 400
};
var options = $.extend(defaults, options);
//Creating a reference to the object
var objContent = $(this);
// The array of pages we will build.
var fullPages = new Array();
// The array of elements for each page, used during pagination calculations.
var pageElements = new Array();
// The height for each page, reset after each page is built.
var height = 0;
var lastPage = 1;
var paginatePages;
// initialization function
init = function ()
{
// Build the array of pages by creating a new page when the sum of the child elements
// height values for each page exceeds the desired page height.
//
// NOTE: This is only an approximation. Haven't figured out why yet. When the
// operation is done there is large variance in the DIV height away from our desired
// height, many of them larger than our desired height.
objContent.children().each(function (i)
{
// Some browsers don't support clientHeight. In those cases, use offsetHeight.
var childHeight = this.clientHeight == 0 ? this.offsetHeight : this.clientHeight;
// If the height of all the children in the page elements array exceeds the desired
// page height, start a new page.
if (height + childHeight > options.height)
{
// Start a new page.
fullPages.push(pageElements);
// Reset the page elements array by initializing it to a new array.
pageElements = new Array();
// Reset the page height accumulatore. for the next page.
height = 0;
}
// Accumulate the child element's height into the height aggregator variable.
height += childHeight;
// Add the child element to the child elements array for the page currently being built.
pageElements.push(this);
});
if (height > 0) {
fullPages.push(pageElements);
}
// wrapping each full page
// $(fullPages).wrap("<div class='page'></div>");
// Wrapping each full page with a DIV. Give the DIV an ID that contains the page number.
$(fullPages).wrap(
function (ndx) {
return "<div class='page' name='pages' id='page_" + (ndx + 1) + "'></div>"
});
// Find the DIV with the maximum height.
var maxDivHeight = 0;
for (var ndx = 1; ndx <= fullPages.length; ndx++) {
var pageN = document.getElementById('page_' + ndx);
// Some browsers don't support clientHeight. In those cases, use offsetHeight.
var divHeight = pageN.clientHeight == 0 ? pageN.offsetHeight : pageN.clientHeight;
if (divHeight > maxDivHeight)
maxDivHeight = divHeight;
}
// Set the height of the content DIV to the maximum height we found plus a little padding.
objContent.height(maxDivHeight);
// hiding all wrapped pages
objContent.children().hide();
// making collection of pages for pagination
paginatePages = objContent.children();
// show first page
showPage(lastPage);
// draw controls
showPagination($(paginatePages).length);
};
// update counter function
updateCounter = function (i) {
$('#page_number').html(i);
};
// show page function
showPage = function (page) {
i = page - 1;
if (paginatePages[i]) {
// hiding old page, display new one
$(paginatePages[lastPage]).fadeOut(options.fadeSpeed);
lastPage = i;
$(paginatePages[lastPage]).fadeIn(options.fadeSpeed);
// and updating counter
updateCounter(page);
}
};
// perform initialization
init();
}
});
})(jQuery);
You can maybe use getBouningClientRect on your element. This will give you the position and size of that element:
var clientRect = element.getBoundingClientRect();
And now you can get the size and position:
var leftPos = clientRect.left;
var topPos = clientRect.top;
var width = clientRect.width;
var height = clientRect.height;
Hope this helps!
Here is a link to more information: https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

Scrollpane on the bottom, css is hacky, javascript is hard

I want to put a bar on the bottom of my page containing a varying number of pictures, which (if wider than the page) can be scrolled left and right.
The page width is varying, and I want the pane to be 100% in width.
I was trying to do a trick by letting the middle div overflow and animate it's position with jquery.animate().
Like this:
Here is a fiddle without the js: http://jsfiddle.net/SoonDead/DdPtv/7/
The problems are:
without declaring a large width to the items holder it will not overflow horizontally but vertically. Is this a good hack? (see the width: 9000px in the fiddle)
I only want to scroll the middle pane if it makes sense. For this I need to calculate the width of the overflowing items box (which should be the sum of the items' width inside), and the container of it with the overflow: hidden attribute. (this should be the width of the browser window minus the left and right buttons).
Is there a way to calculate the length of something in js without counting all of it's childrens length manually and sum it up?
Is there a way to get the width of the browser window? Is there a way to get a callback when the window is resized? I need to correct the panes position if the window suddenly widens (and the items are in a position that should not be allowed)
Since the window's width can vary I need to calculate on the fly if I can scroll left or right.
Can you help me with the javascript?
UPDATE: I have a followup question for this one: Scroll a div vertically to a desired position using jQuery Please help me solve that one too.
Use white-space:nowrap on the item container and display:inline or display:inline-block to prevent the items from wrapping and to not need to calculate or set an explicit width.
Edit:: Here's a live working demo: http://jsfiddle.net/vhvzq/2/
HTML
<div class="hscroll">
<ol>
<li>...</li>
<li>...</li>
</ol>
<button class="left"><</button>
<button class="right">></button>
</div>
CSS
.hscroll { white-space:nowrap; position:relative }
.hscroll ol { overflow:hidden; margin:0; padding:0 }
.hscroll li { list-style-type:none; display:inline-block; vertical-align:middle }
.hscroll button { position:absolute; height:100%; top:0; width:2em }
.hscroll .left { left:0 }
.hscroll .right { right:0 }
JavaScript (using jQuery)
$('.hscroll').each(function(){
var $this = $(this);
var scroller = $this.find('ol')[0];
var timer,offset=15;
function scrollLeft(){ scroller.scrollLeft -= offset; }
function scrollRight(){ scroller.scrollLeft += offset; }
function clearTimer(){ clearInterval(timer); }
$this.find('.left').click(scrollLeft).mousedown(function(){
timer = setInterval(scrollLeft,20);
}).mouseup(clearTimer);
$this.find('.right').click(scrollRight).mousedown(function(){
timer = setInterval(scrollRight,20);
}).mouseup(clearTimer);
});
Thanks Phrogz for this part -- give the image container the white-space: nowrap; and display: inline-block;.
You can calculate the width without having to calculate the width of the children every time but you will need to calculate the width of the children once.
//global variables
var currentWidth = 0;
var slideDistance = 0;
var totalSize = 0;
var dispWidth = (winWidth / 2); //this should get you the middle of the page -- see below
var spacing = 6; //padding or margins around the image element
$(Document).Ready(function() {
$("#Gallery li").each(function () {
totalSize = totalSize + parseFloat($(this).children().attr("width"));// my images are wrapped in a list so I parse each li and get it's child
});
totalSpacing = (($("#Gallery li").siblings().length - 1) * spacing); //handles the margins between pictures
currentWidth = (parseFloat($("#Gallery li.pictureSelected").children().attr("width")) + spacing);
maxLeftScroll = (dispWidth - (totalSize + totalSpacing)); //determines how far left you can scroll
});
function NextImage() {
currentWidth = currentWidth + (parseFloat($("#Gallery li.pictureSelected").next().children().attr("width")) + spacing); //gets the current width plus the width of the next image plus spacing.
slideDistance = (dispWidth - currentWidth)
$("#Gallery").animate({ left: slideDistance }, 700);
}
There is a way to get the browser window with in javascript (jQuery example).
and there is a way to catch the resize event.
var winWidth = $(window).width()
if (winWidth == null) {
winWidth = 50;
}
$(window).resize(function () {
var winNewWidth = $(window).width();
if (winWidth != winNewWidth) {
window.clearTimeout(timerID);
timerID = window.setInterval(function () { resizeWindow(false); }, 100);
}
winWidth = winNewWidth;
});
On my gallery there's actually quite a bit more but this should get you pointed in the right direction.
You need to change your #items from
#items
{
float: left;
background: yellow;
width: 9000px;
}
to
#items {
background: yellow;
}
Then calculate the width very easily with jQuery
// #items width is calculated as the number of child .item elements multiplied by their outerWidth (width+padding+border)
$("#items").width(
$(".item").length * $(".item").outerWidth()
);
and simply declare click events for the #left and #right elements
$("#left").click(function() {
$("#middle").animate({
scrollLeft: "-=50px"
}, 'fast');
});
$("#right").click(function() {
$("#middle").animate({
scrollLeft: "+=50px"
}, 'fast');
});
jsFiddle link here
EDIT
I overlooked that detail about the varying image widths. Here is the correct way to calculate the total width
var totalWidth = 0;
$(".item").each(function(index, value) {
totalWidth += $(value).outerWidth();
});
$("#items").width(totalWidth);

Categories

Resources