Making a Slideshow Rotate - javascript

I'm having trouble with a concept with a HTML5/jQuery slideshow system...
I want the images to constantly rotate, without stopping. The way I have it set up now is just going to the first image by changing the margin-left back to 0 when I run out of slides. I'd much rather have it continue indefinitely.
While I'm at it...Is there a way to read a property from the stylesheet? It'd be better if I could ask a user to point the script to the stylesheet and pull the sizing and stuff from there.
Demo: http://bearce.me/so/slideshow
Script (mainly focus on the CSS version, I can convert it to the jQuery version once I understand how to do it):
// JavaScript Document
var slides = 4; // number of slides
var time = 3; // time per slide (in seconds)
var width = 600; // width of slideshow (ex: 600)
var transition = .5 // transition time (in seconds) (for older browsers only, edit css for newer)
window.onload = function start() {
if(Modernizr.csstransitions) {
cssslide();
} else {
jqueryslide();
}
}
function cssslide() {
document.getElementById("container").style.width=(width * slides) + "px";
var num = 0;
setInterval(function() {
num = (num + 1) % slides;
document.getElementById('container').style.marginLeft = (("-" + width) * num) + "px";
}, time * 1000);
}
function jqueryslide() {
$("#container").width((width * slides) + 'px');
var num = 0;
setInterval(function() {
num = (num + 1) % slides;
$("#container").animate({marginLeft: (("-" + width) * num) + "px"},{duration: (transition * 1000)});
}, time * 1000);
}
EDIT: To clarify, I don't want it to constantly scroll, I want it to scroll, stop for a few seconds, scroll, stop, scroll, stop like it does, but instead of zooming all the way back to the first image, I just want it to keep going.

When your slideshow initializes, use JS to duplicate your first image so that the markup looks like this:
<div id="container">
<img src="setup/slides/portal2.jpg" />
<img src="setup/slides/crysis2.jpg" />
<img src="setup/slides/deadspace2.jpg" />
<img src="setup/slides/acb.jpg" />
<img src="setup/slides/portal2.jpg" />
</div>
Then once the 5th slide (duplicate of slide 1) is visible, clear your interval, reset your margin to 0 and re-initialize your slideshow.

I would seriously rethink your approach. Just tacking on more DOM elements into infinity is seriously inefficient, and would probably be an accessibility nightmare.
I would suggest you check out the jQuery Cycle plugin - it's real easy to implement, and allows you to loop infinitely.

Related

Position element in centre of visible viewport window with overflow-y:scroll

I've rather roughly built this website which uses an effect similar to the iOS Safari tab view to look at various pages of a virtual book. Everything is working fine apart from the fact that I can't centre each page in the visible viewport. For example if you scroll down to the final 'page' and click on it, it jumps to the top of the document, instead of staying in the centre of the visible viewport.
I think this is to do with the fact that the scrollable div uses overflow-y:scroll, but I just can't figure out for the life of me how to fix the problem.
Any help would be greatly appreciated!!
Here's my jQuery:
jQuery(document.body).on('click', '.page', function() { //Change to touchstart
// Generate number between 1 + 2
var randomClass = 3;
var randomNumber = Math.round(Math.random() * (randomClass - 1)) + 1;
// Initialise & Random Number
jQuery(this).addClass("activated").addClass('scaled-' + randomNumber);
// Exiting - Reset All
jQuery(document.body).on('click', '.activated', function() { //Change to Touchstart
jQuery(this).removeClass("activated scaled-1 scaled-2 scaled-3");
});
});
And here is a jsfiddle with all my code in it so you can get a better idea of what I'm trying to achieve.
https://jsfiddle.net/ontu1ngq/
Thanks!
You need to get the amount that #wrapper has been scrolled, so that you can use that to set the top of the .page accordingly. Then, when you remove the .activated class, you will just need to remove the inline top style.
jQuery(document.body).on('click', '.page', function() {
var randomClass = 3;
var randomNumber = Math.round(Math.random() * (randomClass - 1)) + 1;
jQuery(this).addClass("activated").addClass('scaled-' + randomNumber);
var wrapper_scrollTop = $("#wrapper").scrollTop(); //gets amount scrolled
var half_wrapper = $("#wrapper").height()*(0.5); //50% of wrapper height
jQuery(this).css("top",half_wrapper+wrapper_scrollTop);
jQuery(document.body).on('click', '.activated', function() {
jQuery(this).removeClass("activated scaled-1 scaled-2 scaled-3");
jQuery(this).css("top","") //returns top to original value specified in css
});
});
Check out this working fiddle: https://jsfiddle.net/tardhepc/1/

Black space between swaping images

I'm having a issue with the website I'm creating. The truck image at the top is changing on scroll down, but while scrolling and changing the images there appears black space.
1) Images are 1400x600 JPG's, around 70kb each. I didn't lower the resolution because if someone accesses it from a 1920x1080 screen, the truck will be blurry and distorted.
2) The website is still not done, so it's on a free hosting now (000webhost.com), may this cause the images to load slower and the black space to appear?
Here is the website: http://denea.comeze.com/
Here's the script that changes the images, just in case:
var numberofscroll = 0;
var lastScrollTop = 0;
$(document).ready(function () {
var numberofscroll = 1;
var lastScrollTop = 0;
var totalImages = 4;
var dontHandle = false;
$("#home").scroll(function () {
if (dontHandle) return; // Debounce this function.
dontHandle = true;
var scrollTop = $(this).scrollTop();
(scrollTop > lastScrollTop) ? numberofscroll++ : numberofscroll--;
if (numberofscroll > totalImages) numberofscroll = totalImages;
else if (numberofscroll < 1) numberofscroll = 1;
change_background(numberofscroll);
lastScrollTop = scrollTop;
window.setTimeout(function() {
dontHandle = false;
}, 150); // Debounce!--let this handler run once every 400 milliseconds.
});
function change_background(num) {
$("#home").css("backgroundImage", "url('images/movie_" + num + ".jpg')");
};
});
Your Problem has to do with loading time.
Instead of loading the image, when the scroll begins, you can have the images you need already loaded in your page, that way you do not have any loading times, when swapping.
In HTML you have something like this:
<div class="headimg_container>
<img id="image_1" class="headimg" style="display: none" src=".......">
<img id="image_2" class="headimg" style="display: none" src=".......">
<img id="image_3" class="headimg" style="display:block" src"......">
</div>
I used headimg_container as a container element. The class should have a definitve height, so when hiding and showing your images, the container does not collapse.
And in JS you can do something like this:
function change_background(num) {
$(".headimg").hide();
$("#image_" + num).show();
};
The result would be smooth, since you can just swap the visibility of the image-tags, without any delay.
Another solution could be to use sprites, but with a few heavy images, you might want to stick with loading them separately as I suggested above.
Hope that helps!

overflow: hidden; image scrollBy

I had an idea for like a bus window as a fixed frame, about 800px wide, with a parallax city with the content on billboards spaced out so when you scroll between them it allows the parallax to look like bus is moving. The content will be much bigger than the window like a sprite and I'll put forward and back buttons that will scrollBy (x amount, 0). I have a working parallax script and a rough cityscape of 3 layers that all work fine.
I have hit a wall. I am trying to clear a scrollBy animation after it scrolls 1000px. Then you click it again and it goes another 1000px. This is my function.
function scrollForward() {
window.scrollBy(5,0);
scrollLoop = setInterval('scrollForward()',10);
}
So far I can only clear it when it gets to 1000. I tried doing 1000 || 2000 ect but after the first one it goes really fast and won't clear.
Excelsior https://stackoverflow.com/users/66580/majid-fouladpour wrote a great piece of code for someone else with a different question. It wasn't quite right for what the other guy wanted but it is perfect for me.
function scrollForward() {
var scrolledSoFar = 0;
var scrollStep = 75;
var scrollEnd = 1000;
var timerID = setInterval(function() {
window.scrollBy(scrollStep, 0);
scrolledSoFar += scrollStep;
if( scrolledSoFar >= scrollEnd ) clearInterval(timerID);
}, 10);
}
function scrollBack() {
var scrolledSoFar = 0;
var scrollStep = -75;
var scrollEnd = -1000;
var timerID = setInterval(function() {
window.scrollBy(scrollStep, 0);
scrolledSoFar += scrollStep;
if( scrolledSoFar <= scrollEnd ) clearInterval(timerID);
}, 10);
}
Now for step two figuring out how to put this content animation behind a frame.
Not quite sure what your asking here. Perhaps you could provide more relevant code?
I do see a potential issue with your code. You call setInterval('scrollForward()', 10) which will cause scrollForward to be called every 10ms. However, each of those calls to scrollForward will create more intervals to scrollForward creating a sort of explosion of recursion. You probably want to use setTimeout or create your interval outside of this function.
Also, as an aside you can change your code to simply: setInterval(scrollForward, 10). Removing the quotes and the parens makes it a littler easier to read and manager. You can even put complex, lambda functions like:
setInterval(function() {
scrollForward();
// do something else
}, 10);
edit:
So if you know that scrollForward moves the item 10px, and you want it to stop after it moves the item 1000px, then you simply need to stop it has moved that much. I still don't know how your code is actually structured, but it might look something like the following:
(function() {
var moved_by = 0;
var interval = null;
var scrollForward = function() {
// move by 10px
moved_by += 10;
if (moved_by === 1000 && interval !== null) {
clearInterval(interval);
}
};
var interval = setInterval(scrollForward, 10);
})();
If you want to clear it after 1000 or 2000, you simply adjust the if statement accordingly. I hope that helps.

Animation starts moving out of position after some time

I am trying to create a sort of slideshow animation. I have the codes here: jsFiddle.
These tablets would rotate around.
The problem is that, at random times, the animation will move out of line. The wrong tablets undergo wrong animations. Here are the screenshots:
And this is how it looks like when the animations goes wrong
The main problem is I don't understand why the animation would go wrong random times. In my computer it will run properly for hours, but in other cases (especially on Safari).
You could store the expected final css values for each animated el and then in the animate callback set these values, so for each animated el something like
var el = $(selector);
el.data("finalCSS", { your expected final CSS values })
$("selector").animate({animation properties}, function() {
el.css(el.data("finalCSS")).data("finalCSS", undefined);
})
This doesn't help with figuring out why it's happening (but I can't recreate the issue myself), but provides a failsafe to make sure the layout doesn't break;
I believe this happens when you try to animate before the previous animation has ended. Use jQuery stop() just before you animate. For example:
$('#animatingDiv').stop(false, true).animate({height:300}, 200, callback);
The first param(false) will empty the animation queue on that element and the second param(true) will jumps to the end of current animation before starting a new animation.
You can do this with far less code and far fewer headaches.
1. Store your tablet position attributes in classes
.tablet1{
height:100px;
width:140px;
margin-left:-540px;
top: 200px;
z-index:10;
}
2. Use a general function to handle all your transitions.
JQuery UI will do all the work for you if you use switchClass
switchTabletsRight = function(){
var i, next, max = 5;
for(i = 1; i <= max; i++){
next = (i < max)? i + 1 : 1;
$(".tablet" + i).switchClass("tablet" + i, "tablet" + next);
}
};​
Here's the JSfiddle proof of concept: http://jsfiddle.net/nRHag/4/
You are setting CSS positions to decimal values.
img_w = $("#tablet"+num+" img").width();
img_w = img_w *140 / 600;
img_h = $("#tablet"+num+" img").height();
img_h = img_h *140 /600;
...
var new_width = $(this).width() * 140 / 600;
$(this).css('width', new_width);
var new_height = $(this).height() * 140 / 600;
$(this).css('height', new_height);
Your division could be cause decimal results which have different effects in different browsers. Sub pixel CSS positioning may be creating your unintended errors.

Adjust top position according to height of div with javascript

function jsiBoxAdjustTop()
{
var top
if ( jsiBox.preloadImg.height <= 699){
top = 216;
}
else{
top = 17;
}
jsiBox.boxNode.style.top = (top) + 'px';
}
I'm using that function to adjust a div's top position depending on the image that is in it's height. It's on a light box sort of script so every time I click the next button, a new image which could either be taller or smaller appears. It's working alright and it adjusts its position when the image is taller but my problem is it just jumps to that position. I'm really new to javascript so can anyone help me out to make this as if it's travelling/animating to it's position? I tried using setTimeOut but I think I was doing it wrong. I'd really love to know what I'm doing wrong.
Here's the full script if that helps. Link
you can use jQuery or YUI to do animate, such as
jQuery(jsiBox.boxNode).animate({'top': top}, 3000);
or you can write some simple code with setTimeout just for this case;
following code assume the begin top is 0.
var boxStyle = jsiBox.boxNode.style;
function animateTop(to) {
boxStyle.top = parseInt(boxStyle.top, 10) + 1 + 'px';
if (parseInt(boxStyle.top, 10) != to) {
setTimeout(function() {
animate(to);
}, 50);
}
}
animateTop(top);

Categories