jquery infinite slider images - javascript

I'm trying to create an infinite slider using jquery. My page has some tags, with the width equal to the window width.
I want to slide every image after 10 seconds, and when the last image comes up and it's time for the first image to show, I want it to come still from the right.
Now I created a div with a big width, 10000px to hold my unordered list of images and they have display:none. My question is why when I'm giving margin-left: -1000px for one list item, the images appear to overlap one above the other, instead of appearing one after the other. I tried to take a screenshot but I don't know what is happening with my dropbox.
This is my CSS:
.slider {
position: relative;
height: 498px;
/*display: inline-block;*/
overflow: hidden;
}
.slider-list {
/*display: inline-block;*/
float: left;
padding: 0;
margin: 0;
width: 10000px
/*height: 496px;*/
}
.slider-list li{
display: inline-block;
/*float: left;*/
/*width: 100%;*/
height: 496px;
z-index: 1;
And here is my HTML:
<div class="slider">
<ul class="slider-list">
<li><img class="homepage-img"src="images/homepage.jpg"></li>
<li><img class="homepage-img"src="images/image1.jpg"></li>
<li><img class="homepage-img"src="images/image2.jpg"></li>
<li><img class="homepage-img"src="images/image3.jpg"></li>
<li><img class="homepage-img"src="images/image4.jpg"></li>
</ul>
The div with the class .slider will close after some more elements.
UPDATE:
This is my jQuery code since I written this post:
$(document).ready(function(){
slide();
});
slide = function() {
var img = $('.homepage-img');
var content = $('.slider-content');
var slider = $('.slider-list');
var elements = $('.slider-list li').children();
var auto_slide_speed = 100;//ms
var timer;
var i = 0;
img.width($(window).width());
$("li").width($(window).width());
img.height($('.slider-list').height());
content.height($('.slider-list').height());
var img_width = $('.slider-list li').outerWidth();
console.log($('.slider-list li').length);
console.log(elements);
//calculam margin-left = -latimea unei imagini
// while(1)
// {
var left = parseInt(slider.css('margin-left')) - img_width;
for(i = 0; i <= $('.slider-list li').length; i++)
{
console.log(i);
slider.animate({
"margin-left": "+=" + left},
1500,
function() {
// $('.slider-list li:last').after($('.slider-list li:first'));
// $('slider').css({'margin-left' : '0px'});
});
// left = left + left;
// $('slider li').append($(elements[i]).clone());
}
console.log(i);
}
With this, my slider ony goes as far as my list goes. How do I append the first item after the last item and so on so it can be infinite?

If you are targeting modern browsers that support transitions and transforms i would do it that way..
Demo at http://jsfiddle.net/gaby/dbLu5/
jQuery
var slides = $('.slider-list li'); // cache a reference to the slides
setInterval(function(){
var current = slides.filter('.current'), // find slide in view
next = current.next(); // find next slide
if (!next.length){next = slides.first();} // loop if at last slide
slides.removeClass('off'); // reposition already viewed slides to the right
current.removeClass('current').addClass('off'); // set current slide to animate left
next.removeClass('off').addClass('current'); // set next slide to slide in view
}, 10000); // set the interval
CSS (you need to add vendor prefixes for the transform and transition properties)
.slider-list {
position:relative;
padding: 0;
margin: 0;
overflow:hidden;
height: 496px;
}
.slider-list li {
width:100%;
height: 100%;
display: block;
z-index: 1;
transition:transform 1s;
transform:translateX(100%);
left:0; top:0;
position:absolute;
overflow:hidden;
}
.slider-list li.current{
transform:translateX(0%);
z-index:100;
}
.slider-list li.off{
transform:translateX(-100%);
z-index:100;
}

Here is a FIDDLE that will get you started.
Put all your images in a hidden div
Clone them and put them in the visible div
Animate the image by changing the left margin
You can adjust the time between images by the set interval function
You can adjust the slidein time by the animate time.
Because it's an infinite loop, I put the button in to stop the animation any time you want.
JS
var pictxtnumber = 1;
loadpictxt(pictxtnumber);
var fadeintime = 500;
animatediv();
function animatediv()
{
var number = 0;
var interval = setInterval(function() {
pictxtnumber = pictxtnumber + 1;
if(pictxtnumber > 6)
{
pictxtnumber = 1;
}
loadpictxt(pictxtnumber);
$('#stopanim').on('click', function(){
clearInterval(interval);
});
}, 1000);
}
function loadpictxt(num)
{
$('.picturediv').html('');
$(".hiddenimage img:nth-child(" + num + ") ").clone().appendTo('.picturediv');
$('.picturediv img').css('margin-left', '100px');
$('.picturediv img').animate({marginLeft: "0"}, 100);
}

I've made two simple jquery plugins for that:
https://github.com/lingtalfi/jItemSlider
https://github.com/lingtalfi/jInfiniteSlider
I recommend the item slider because the items are forced to be aligned, and it's simpler in the end.
Now to answer your question: How do I append the first item after the last item and so on so it can be infinite?
You could just display your slider items two times (or more) in a row.
Given your html code:
var jSliderList = $(".slider-list");
var jSliderOriginalItems = $("li", jSliderList); // keep track of this one
function init(){
jSliderList.append(jSliderOriginalItems.clone()); // should work, not tested
}
Then with css, you would narrow the slider to the width of your choice.
Suggestions:
I would suggest that you append a page rather than just one item.
A basic approach would be to encapsulate things into functions, like this:
slideToRight()
appendItemsToTheRight()
removeUnecessaryItemsToTheLeft()
slide()
To perform the slide, you could use css transitions.
In your css, put something like this:
.sliderContainer {
transition: transform 2s ease;
}
And then in your js code, to slide, just use a function such as:
function moveSlider(the_offset) {
jSliderContent.css({
transform: "translate3d(" + the_offset + "px, 0px, 0px)"
});
}
Now to actually append an item, you could use a renderItem function to generate them, instead of cloning things.

Related

Changing the size of the image in the sticky header when scrolling down

On the website (please don't share), in WordPress, I set a sticky header using CSS
header#masthead {
position: sticky;
top: 0;
left: 0;
right: 0;
z-index: 10000;
}
This works correctly. However, the image in the header is too big, that's why I resized it with an animation when scrolling down
jQuery(document).ready(function() {
jQuery(function() {
var $nav = jQuery('#masthead .custom-logo');
var height_original = jQuery('#masthead .custom-logo').css("height").replace("px","");
var height_small = height_original * 0.666;
var width_original = jQuery('#masthead .custom-logo').css("width").replace("px","");
var width_small = width_original * 0.666;
jQuery(document).scroll( function() {
var value = jQuery(this).scrollTop();
if ( value > 0 ){
$nav.stop().animate({height:height_small,width:width_small},100);
} else if (value == 0 ) {
$nav.stop().animate({height:height_original,width:width_original},100);
}
});
});
});
But, it doesn't work properly.
I primarily use Opera GX, where it behaves like this - when scrolling down, the animation is slowed down. Also, if you just scroll down a little, the animation doesn't run all the way and the image goes back to its original size, scrolling up works without a problem.
The strange thing is that I've also tried it in Firefox, Chrome and Edge. It behaves differently in everyone, but nowhere does it work 100% correctly.
What is wrong with the code please?
Thank you
I think instead of that long jquery code you can use this simple javascript code with some css to get the results you want:
I hope this helps you to reach what you looking for :)
JS
// Add a class to the header when scrolling
let header = document.querySelector('header');
window.addEventListener('scroll' , function () {
let window_top = this.scrollY;
if (window_top == 0) {
header.classList.remove('resize');
}else {
header.classList.add('resize');
}
});
CSS
/* these are the default styles (when the user doesnt scroll down yet) */
header#masthead {
position: sticky;
top: 0;
left: 0;
right: 0;
z-index: 10000;
transition: .3s;
}
header#masthead img{
transition: .3s; /*here i added transition to give the image a smooth animation*/
}
/* these are the styles when the user scrolls */
header#masthead.resize img{
height: 50px; /* <=== here i gived the image a smaller size */
}

How to make autosliding carousel thumbnail change background image when active

my question has 3 parts. Any assistance with any part of this JS problem would be greatly appreciated. I am attempting to learn and comprehend JS by trial and error.
I've created this nice looking travel landing page, https://portfolioprime.github.io/Nature%20carousel/glidejs.html with a thumbnail carousel which uses Glide.js, which is really cool and works well. The carousel moves to the left and has arrow buttons to manually control the slide.
But I've been trying to implement a vanilla JS carousel slider,but I am failing miserably. Been struggling for 2 days and the best I can achieve is getting a single carousel item moving left and right. See https://portfolioprime.github.io/Nature%20carousel/.
What I'd like is to get the carousel sliding left automatically, with arrow buttons to manually control the slider.
I'm targeting all the carousel-items with querySelectorAll('.carousel-items') and adding left:-274px to the carousel container glide__slides.
Here's my JS code.
// var & event-listener buttons
document.querySelector(".left").addEventListener("click", slideLeft);
document.querySelector(".right").addEventListener("click", slideRight);
// Function slide left
function slideLeft(left) {
document.querySelector('.glide__slides').style.left = left;
}
// Function slide left
function slideRight(right) {
document.querySelector('.glide__slides').style.left = right;
}
Secondly, I'd like to have an active carousel-item, which when active automatically changes the background Image.
Right now I have the hero.style.background = var; and I've got it changing onclick with onclick = function('01.jpg') on each carousel item.
Here's the code.
// Change Hero Img
function heroChange(hmmm) {
var hero = document.querySelector('.hero');
hero.style.background = hmmm;
}
So I guess I would add EventListeners to the carousel-items and add an active class to the carousel-item like so,
var slides = document.querySelectorAll('.carousel-items');
function changeBgImg() {
slides.forEach(s => s.classList.remove('active');
this.classList.add('active');
//change the bg image === this
//But I have no idea how to do that
}
Thirdly I've got the content, background and carousel indicators using the same functions above but it seems like really dirty code. The HTML has each .carousel-item, there are ten of them, calling 4 functions each. It looks like this:
<div class="glide hero-carousel">
<div class="glide__track" data-glide-el="track">
<ul class="glide__slides">
<li class="glide__slide carousel-item"
onclick="heroChange('url(images/02.jpg) bottom/cover no-repeat');
number('01');
h4('Destination Shire');
h1('Valley<br> of Dreams');">
<div class="carousel-text">
<p>Destination Shire</p>
<h3>Valley<br> of Dreams</h3>
</div>
</li>
<li class="glide__slide carousel-item"
onclick="heroChange('url(images/03.jpg) bottom/cover no-repeat');
number('02');
h4('Destination Westwood');
h1('Misty<br> Woodlands');">
<div class="carousel-text">
<p>Destination Westwood</p>
<h3>Misty<br> Woodlands</h3>
</div>
</li>
</ul>
</div>
</div>
So it looks pretty yucky. It works though, but I would love to find a more elegant way of achieving this by putting all of these functions into one function that does each part in sequence.
Lastly, I'd want to get transition on-click animations going but that's another kettle of fish entirely.
So that's it. Whew!
Thanks for taking the time guys, I appreciate it. Any help you can provide is going to make me a better designer. There are actually a bunch of projects I have will benefit from the answers.
If you can provide help with at least Part 2 & 3: cleaning up the code into 1 function and getting the bg-image changing on the active class that would be a big big help.
There's just so much that JS can do and I'm not finding the answers on Google and youTube.
Thank you again.
An Update:
I have edited the slider by by using margin-left as shown by this question:
vanilla javascript carousel not sliding
// var & event-listener buttons
document.querySelector(".left").addEventListener("click", slideLeft);
document.querySelector(".right").addEventListener("click", slideRight);
let marginLeft = 0;
const slides = document.querySelector('.glide__slides');
// Function slide left
function slideLeft() {
marginLeft += 264;
slides.style.marginLeft = marginLeft + 'px';
console.log(getComputedStyle(slides).marginLeft);
}
// Function slide Right
function slideRight() {
marginLeft -= 264;
slides.style.marginLeft = marginLeft + 'px';
console.log(getComputedStyle(slides).marginLeft);
}
This has now got the carousel moving manually 1 slide at a time.
Still not fully understanding why my previous code above didn't work. If anyone can explain that to me that would be great.
I'm still left with some issues:
Autosliding and looping at the end of the slides.
Having the active slider change the background automatically. At this point it only changes onclick.
Finding a way to tidy up the function calls and functions.
The question asks for various ideas on how to simplify code and how to use native JavaScript to create a slider that rolls continuously.
The code originally used glider and it may be something simpler would be sufficient to get the desired result, for example using animationend event to change the background when a slide gets to the left hand side. However, eating the elephant slowly I'll tackle the yucky code (part 3) first.
Although the HTML looks rather daunting, 4 calls on a click for every li element for example, it is currently what is required so let's investigate creating it at run time. This gives us more easily maintainable code. For example, if we want to remove a slide, or alter the order of slides or add one we can just alter the slider array defined below and JavaScript will do the rest.
Part 1 of the question asked about sliding. We slide the whole ul element using CSS animation defined something like this, where 33vw is the total width of a slide (inc. margins/padding)
#keyframes sliding0 {
0% { left: 0; }
30% { left: 0; }
100% { left: -33vw; }
}
and we add an event listener to the element to trap animationend events because when the ul has slid one slide's width we want to change the hero image, and we want to put the slide that has just disappeared onto the back of the infinie sliding will work. We then set the animation running again.
See the snippet for details on how this and other events are dealt with. It also shows how the changeHero function can work which was part 2 of the question. Note, the snippet works more or less in the SO environment, though occasionally hover action is partially ignored. Running the code on your own machine it should be fine though.
<!DOCTYPE html>
<html>
<head>
<style>
#keyframes sliding0 {
0% { left: 0; }
30% { left: 0; }
100% { left: -33vw; }
}
#keyframes sliding1 {
0% { left: 0; }
30% { left: 0; }
100% { left: -33vw; }
}
body {
background-repeat: no-repeat no-repeat;
background-size: cover;
background-position: center center;
}
div .glide_track {
position: relative;
width: 100vw;
overflow-x: hidden;
}
ul {
position:relative;
left: 0;
width: 330vw;
height:100vh;
animation-name: sliding0;
animation-duration: 3s;
animation-delay: 0s;
animation-iteration-count: 1;
animation-timing-function: linear;
margin: 0;
padding: 0;
list-style-type: none;
}
li {
position: relative;
left:0;
top:0;
float:left;
width: 32vw;
height:30vw;
display: inline-block;
margin: 0;
margin-right: 1vw;
padding: 0;
background-size: cover;
background-repeat: no-repeat no-repeat;
background-position: center center;
}
</style>
</head>
<body>
<script>
// we put the two lots of text and the image url for each slide in an array in the order they are to be shown
// this makes it easier to maintain when you want to add or remove a slide or change their order
// we only have one slider at the moment but this makes it more general
// these are the offsets in the array describing a slide. Done as indexes rather than named as easier to set up sliders array
const img = 0;
const text1 = 1;
const text2 = 2;
const sliders = [
[
['https://ahweb.org.uk/boxfordmosaic.jpg','Shire','Valley<br> of Dreams'],
['https://ahweb.org.uk/gear-in-turbine-house-reading.jpg','Westwood','Misty Woodlands'],
['https://ahweb.org.uk/tricycle-in-abbey-ruins.jpg','Shire','Valley<br> of Dreams'],
['https://ahweb.org.uk/boxfordmosaic.jpg','Shire','Valley<br> of Dreams'],
['https://ahweb.org.uk/gear-in-turbine-house-reading.jpg','Westwood','Misty Woodlands'],
['https://ahweb.org.uk/tricycle-in-abbey-ruins.jpg','Shire','Valley<br> of Dreams'],
['https://ahweb.org.uk/boxfordmosaic.jpg','Shire','Valley<br> of Dreams'],
['https://ahweb.org.uk/gear-in-turbine-house-reading.jpg','Westwood','Misty Woodlands'],
['https://ahweb.org.uk/tricycle-in-abbey-ruins.jpg','Shire','Valley<br> of Dreams'],
['https://ahweb.org.uk/tricycle-in-abbey-ruins.jpg','Shire','Valley<br> of Dreams']
]
];
// go through each slider and create its outer divs and its ul element
sliders.forEach(createSlider);
function createSlider(slider,sliderno) {
const div1 = document.createElement('DIV');
const div2 = document.createElement('DIV');
const ul = document.createElement('UL');
div1.classList.add("glide","hero-carousel");
div2.classList.add("glide_track");
div2.setAttribute("data-glide-el","track");
div1.appendChild(div2);
div2.appendChild(ul);
document.body.appendChild(div1);
ul.classList.add("glide__slides");
ul.addEventListener("animationend", animationEnd);
slider.forEach(createLi);
function createLi(slide,slideNo) {
const li = document.createElement('LI');
li.classList.add("glide__slide","carousel-item");
li.style.backgroundImage='url('+slide[img]+')';
li.addEventListener("click",slideClicked);
li.addEventListener("mouseover",slideHovered);
li.addEventListener("mouseout",slideUnhovered);
li.setAttribute('data-slideno','0' + slideNo);//! needs generalising if you have >10 slides !
ul.appendChild(li);
const div = document.createElement('DIV');
const p = document.createElement('P');
const h3 = document.createElement('H3');
p.innerHTML = slide[text1];
div.appendChild(p);
h3.innerHTML = slide[text2];
div.appendChild(h3);
li.appendChild(div);
}
}
// this is for testing, in real version use whatever required (i.e. whichever element is to have the hero image)
function ahHeroChange(backgroundImage) {
document.body.style.background = backgroundImage + " bottom/cover no-repeat";
}
function slideClicked(event) {
var slide = event.target;
var slideNo = slide.getAttribute('data-slideno');
// make the hero image the same as the slide's
ahHeroChange(slide.style.backgroundImage);
/* I don't know what these functions do - they were executed in the original on a click
number(slideno);
h4(slide.firstElementChild.querySelector('p').innerHTML);// text1 of the slide is passed to h4
h1(slide.firstElementChild.querySelector('h3').innerHTML;// text2 of the slide is passed to h1
*/
}
function slideHovered(event) {
var slide = event.target;
var slider = slide.parentElement;
slider.style.animationPlayState = 'paused';
ahHeroChange(slide.style.backgroundImage);
}
function slideUnhovered(event) {
var slide = event.target;
var slider = slide.parentElement;
//restore the hero image to the first one in the slider
ahHeroChange(slider.firstElementChild.style.backgroundImage);
//get the animation running again
slider.style.animationPlayState = 'running';
}
function animationEnd(event) {
//find the element that was clicked (it will be a ul element representing a slider)
var slider = event.target;
//take the first slide off the list and put it back at the end
slider.append(this.firstElementChild);
//change the hero image to the slide which is now the leftmost - use modified heroChange in the final version
document.body.style.backgroundImage = this.firstElementChild.style.backgroundImage;
// toggle the animationName (to an identical keyframes action) to force the animation to start again
slider.style.animationName='sliding'+(Number(event.animationName.replace('sliding',''))+1)%2;
}
</script>
</body>
</html>

Image animate down javascript (no jQuery)

I know how to fix the animation that goes down only when the image is showing up in the window with jQuery, but now I want to do that with JavaScript. Struggling with that. The image must be fluently go down (+50px for 1.6 seconds). Have googling around, but most of them are done with jQuery I suggest and that is not what I want. Furtermore the animation should start when the scrollTop is between 600px and 800px.
function scrollFunction() {
var animate = document.getElementById("picture");
var position = 0;
var top = 0;
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
if(scrollTop > 600 && scrollTop < 800){
position++;
animate.style.top = position + "50px";
} else {
stop();
}
}
function stop() {
clearTimeout(animate);
}
#picture {
width: 100%;
height: auto;
top: -5px;
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
margin-bottom: 20px;
}
<div class="col-sm-12 col-xs-12">
<h1 class="responsive-h1">Mi<span class="logo-orange"> Pad2</span></h1>
<p class="edition-title above-text-black">Black Edition</p>
<img src="Img/picture.jpg" id="picture"/>
</div>
jsFiddle : https://jsfiddle.net/n1q3fy8w/
Javascript
var imgSlide = document.getElementById('slidedown-image');
var slideDown = setInterval(function() {
var topVal = parseInt(window.getComputedStyle(imgSlide).top, 10);
imgSlide.style.top = (topVal + 1) + "px";
}, 15);
setTimeout(function( ) { clearInterval( slideDown ); }, 1600);
You get the element first, after that you setup a setInterval which will basically move our img downwards, we then also set a setTimeout which after 1600ms remvoes the slideDown interval and the image stops. Your image however may need position: absolute.
The above answer will only work in Chrome, this however should work in all browswers
jsFiddle : https://jsfiddle.net/n1q3fy8w/1/
javascript
var imgSlide = document.getElementById('slidedown-image');
var slideDown = setInterval(function() {
var topVal = parseInt(imgSlide.style.top, 10);
imgSlide.style.top = (topVal + 1) + "px";
}, 15);
setTimeout(function( ) { clearInterval( slideDown ); }, 1600);
Ok so getComputedStyle only works in chrome, so to get this to work on all other browsers, you have to specifically set the css property on the element and not via CSS.
When you use javascript to access an element and change its style like so element.style.bottom = '150px' the .style gets you all of the css values for your inline styles on that element, so any css changes on an element that is done via a .css/.less file you can't access via javascript.
So all the above code does is we set a top: 0 on the element itself and in our code we use imageSlide.style.top instead of chrome's window.getComputedStyle
Have you considered using a CSS transition? if you are changing the value of top you should be able to add transition: top 1.6s in your css (to picture). (Then the vendor prefixed versions when you get it working)

How to load an initial set of images, then animate between them randomly without jQuery

On my page I have a gallery (just a div) with several images on it. I want to show the first 9 images immediately, then load more images and use CSS transitions to animate between the existing images.
Loading the initial images is easy but I do not know the best way to load the next set of images and then start animating (using the CSS Transform property). So far this is what I have:
HTML (abbreviated):
<div id="mainContainer">
<div class="imageHolder"><img class="homeImages" src="test.png"></div>
<div class="imageHolder"><img class="homeImages" src="test1.png"></div>
<div class="imageHolder"><img class="homeImages" src="test3.png"></div>
</div>
CSS (abbreviated):
img {
display: inline;
position: relative;
margin: 0;
padding: 0;
width: 30%;
}
.changed.opaque {
opacity: 0;
border: 2px solid red;
}
I am looking to do a variety of effects, the most simple one would be to change the opacity and fade one image over the other. To load the next set of images I have this:
Javascript:
var imageArray = [
'test2.png',
'test3.png',
'test4.png',
'test5.png',
'test6.png',
];
var imageNodeArray = [];
for(var i = imageArray.length - 1; i >= 0; i -= 1) {
var img = new Image();
img.onload = function() {
imageNodeArray.push(this);
};
img.src = imageArray[i];
}
document.onclick = function() {
imageNodeArray[0].setAttribute('class', 'changed.opaque');
divs[0].appendChild(imageNodeArray[0])
}
This does add an image to my mainContainer however, even though I can tell from devTools that it has the changed.opaque class applied to it, no opacity is shown on the added image.
I am curious about this. I would also like to know the best way to "stack" images to have a bunch to animate through. I am not sure that appending child is right.... Thank you
function animate() {
var index = Math.floor((Math.random() * document.querySelectorAll('#mainContainer > .imageHolder').length + 1));
var current = document.querySelector('.top');
var next = document.querySelector('.imageHolder:nth-of-type(' + index + ')');
current.className = "imageHolder";
next.className += "top";
}
Should be able to handle and switch between any dynamically inserted images.
Currently using:
.imageHolder {
display: none;
}
.top {
display: inherit;
}
to switch the image is just a simple implementation.
Here's the working fiddle: http://jsfiddle.net/e9dxN/1/
Alternative implementation: http://jsfiddle.net/e9dxN/6/

Strange behaviour of "position: relative" when zooming. What's happening?

The Fiddle: http://jsfiddle.net/4WFrJ/
My Problem:
I can't wrap my head around the behaviour of this setup.
When I zoom in, the images tend to move faster, but when I zoom out, they don't move at all. Sometimes they just stop at 9.xxxxxx, even though I told them to move only by one pixel. Can you explain this?
My browser is Chrome.
My Aim: achieve a fluid motion with the images disappearing when out of bounds of the parent element, whatever the magnification percentage.
I am in search of the basic rules, that govern these strange processes, from which I hope to learn new things.
The Code:
HTML:
<div id = "presentation">
<ul>
<li class = "pres-item"> <img class = "pres-image" src = "../img/presentation/image1.jpg"> </li>
<li class = "pres-item"> <img class = "pres-image" src = "../img/presentation/image2.jpg"> </li>
<li class = "pres-item"> <img class = "pres-image" src = "../img/presentation/image3.jpg"> </li>
<li class = "pres-item"> <img class = "pres-image" src = "../img/presentation/image4.jpg"> </li>
</ul>
</div>
CSS:
html, body {
margin: 0;
}
#presentation {
padding: 10px;
width: 900px;
margin: 50px auto;
overflow: hidden;
}
#presentation ul {
list-style-type: none;
margin: 0;
}
#presentation ul li {
display: inline-block;
}
.pres-item {
height: 150px;
width: auto;
position: relative;
left: 0;
}
.pres-image {
width: inherit;
height: inherit;
}
JS (with jQuery):
$(document).ready(function(){
var presentation = $('#presentation');
var interval = setInterval(function() {
console.log('intervaling');
$('.pres-item').css('left', '+=1');
}, 60);
});
The Image:
The Thanks:
THANKS PEOPLE (in advance)
<script>
// too much code, but it explains..
// do this in ur interval...
var getCurrent_left = $('.pres-item').css('left');
var newCurrent_left = getCurrent_left.split['px'];
var newCurrent_left = parseInt(newCurrent_left[0]) + 1;
var newCurrent_left = parseInt(newCurrent_left);
$('.pres-item').css({"left", newCurrent_left});
// you can use parseFloat(var, 2) for decimal
</script>
My Problem:
When I zoom in, the images tend to move faster, but when I zoom out, they don't move at all.
I'm not sure this is actually a problem. They appear to move slower when zoomed out because they travel fewer screen pixels for each viewport pixel.
Sometimes they just stop at 9.xxxxxx, even though I told them to move only by one pixel. Can you explain this?
Apparently Chrome does not always return that CSS property as an integer. You can see the same effect in this code:
var presentation = document.getElementById('presentation');
var items = presentation.getElementsByClassName('pres-item');
var interval = setInterval(function () {
[].forEach.call(items, function (x) {
var lastLeft = getComputedStyle(x, null).getPropertyValue('left');
console.log(lastLeft);
x.style.left = (parseFloat(lastLeft) + 1) + 'px';
})
}, 60);
I'm not sure if this is a problem or not. You could easily avoid it by keeping track of the offset in a separate variable and incrementing it during your loop instead of computing it from the element's current style.
var presentation = $('#presentation');
var left = 0;
var interval = setInterval(function() {
++left;
$('.pres-item').css('left', left + 'px');
}, 60);

Categories

Resources