Improve slide effect - javascript

I have created a simple slider
html
<div id="sldvid1" class="slider" >
<img picnum="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png" />
<img picnum="2" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png" />
<img picnum="3" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png" />
</div>
<hr>
<div id="sldvid2" class="slider" >
<img picnum="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png" />
<img picnum="2" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png" />
<img picnum="3" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png" />
</div>
$
var timer1 = setInterval(runSlide, 1000);
var curnum = 1;
function runSlide()
{
curnum = $(".slider img:visible").attr('picnum');
//$("#sldvid1 img[picnum=" + curnum + "]").fadeOut();
if(curnum == 3){
curnum = 1;
}
else
{
curnum++;
}
// $(".slider img").hide();
//$(".slider img[picnum=" + curnum + "]").show();
$(".slider img").hide();
$(".slider img[picnum=" + curnum + "]").show();
//console.log(curnum);
}
CSS
.slider{
height:50px;
}
Demo
http://jsfiddle.net/mparvez1986/vf401e2y/
Everything is working fine, I just need some one to improve effect so that it could effect like moving from left to right, I tried with some effect, but it seems it required some css manipulation as well
Thanks

I modified your code to create a carousel where images are slid in and out. I accomplished this by animating the margin-left CSS property with jQuery. I specified a size for the .slider class and used overflow: hidden; to ensure the sliding images were not displayed outside of it.
If you wish, you can change the transition effect by changing the CSS property that is animated and ensuring that the elements are in the correct position for the animation before it begins.
You can also change the speed of the animation by changing the magic number 1000 that I've left in the calls to animate. This number is specified in milliseconds.
By the way, I should point out that while custom HTML attributes are allowed in HTML5 they should begin with data-; they are called data attributes.
jsfiddle
HTML
<div id="sldvid1" class="slider">
<img class="active" data-slide-to="0" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png"/>
<img data-slide-to="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png"/>
<img data-slide-to="2" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png"/>
</div>
<hr>
<div id="sldvid2" class="slider">
<img class="active" data-slide-to="0" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png"/>
<img data-slide-to="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png"/>
<img data-slide-to="2" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png"/>
</div>
CSS
.slider {
position: relative;
width: 50px;
height: 50px;
overflow: hidden;
}
.slider img {
display: none;
width: 100%;
position: absolute;
}
.slider .active {
display: inline-block;
}
.slider .sliding {
display: inline-block;
}
JavaScript
var timer = setInterval(runSlide, 2000);
function runSlide() {
// Slide each slider on the page.
$(".slider").each(function (index, element) {
// Get the elements involved in the slide.
var numChildren = $(this).children().length;
var activeChild = $(this).children(".active");
var activeSlideTo = $(activeChild).attr("data-slide-to");
var nextSlideTo = (parseInt(activeSlideTo) + 1) % numChildren;
var nextChild = $(this).find("*[data-slide-to=" + nextSlideTo + "]");
// Prepare for slide.
$(activeChild).css("margin-left", "0%");
$(nextChild).css("margin-left", "-100%");
$(activeChild).addClass("sliding");
$(nextChild).addClass("sliding");
$(activeChild).removeClass("active");
// Slide using CSS margin-left.
$(activeChild).animate({"margin-left": "100%"}, 1000, function () {
$(this).removeClass("sliding");
});
$(nextChild).animate({"margin-left": "0%"}, 1000, function () {
$(this).addClass("active");
$(this).removeClass("sliding");
});
});
}

Ended with following
setInterval(function() {
$('#sldvid1 > img:first')
.fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo('#sldvid1');
}, 3000);

Related

Self-made image carousel not looping

So I have a weird bug with my self-made jQuery image carousel. I also have already checked the suggested similar topics and they didn't help. So it's a simple six images with a next arrow and prev arrow. If you get to the end using the prev arrow then it loops to the last image successfully, but if you try to go back to the first image from the last using the next arrow it takes two extra clicks and after the first click it screws up the page and makes everything out of order. Any suggestions?
JavaScript
$('.arrow-prev').click(function() {
var currentSlide = $('.active-slide');
var prevSlide = currentSlide.prev();
if(prevSlide.length === 0) {
prevSlide = $('.slide').last();
}
currentSlide.removeClass('active-slide');
prevSlide.addClass('active-slide');
});
$('.arrow-next').click(function() {
var currentSlide = $('.active-slide');
var nextSlide = currentSlide.next();
if(nextSlide.length === 0) {
nextSlide = $('.active-slide');
}
currentSlide.removeClass('active-slide');
nextSlide.addClass('active-slide');
});
(Relevant) HTML
<div class="slider">
<div class="slide active-slide">
<img src="img/image-2.jpg">
</div>
<div class="slide">
<img src="img/image-3.jpg">
</div>
<div class="slide">
<img src="img/image-4.jpg">
</div>
<div class="slide">
<img src="img/image-5.jpg">
</div>
<div class="slide">
<img src="img/image-1.jpg">
</div>
<div class="slide">
<img src="img/image-6.jpg">
</div>
<img src="img/Arrow-Prev.png" width="75px" height="75px">
<img src="img/Arrow-Next.png" width="75px" height="75px">
</div>
(Relevant) CSS
.slider {
display: block;
margin-left: 9%;
}
.slide {
display: none;
}
.active-slide {
display: block;
}
.slider img {
max-width: 90%;
margin-top: 15px;
}
.slider .arrow-prev {
margin-left: 13%;
}
.slider .arrow-next {
float: right;
margin-right: 25%;
}
You have two issues with your code for the next function.
The next() element of the last slide will be the a tag therefore the length is always > 0. You can evaluate if the next is an "slide" element:
var nextSlide = currentSlide.next('.slide');
If nextslide doesn't exist you need to go to the first() element:
nextSlide = $('.slide').first();
Updated Demo
Thanks to #Jonathan Lam for the demo
nextslide=$(".activeslide")
in your if statement will not work because the activeslide is your current slide. The script will do nothing
What about
nextslide=$(".slide").first()
?

jQuery - How to make images overlap when fading in and out?

So I have this:
https://jsfiddle.net/ysr50m2m/1/
Html
class="photoset">
<img src="http://inspirebee.com/wp-content/uploads/2013/04/animal-fashion-parade.jpg" />
<img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals18.jpg" />
<img src="http://inspirebee.com/wp-content/uploads/2013/04/animal-in-fashion.jpg" />
<img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals20.jpg" />
</div>
<div class="photoset">
<img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg" />
<img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals14.jpg" />
<img src="http://inspirebee.com/wp-content/uploads/2013/04/animal-fashion.jpg" />
<img src="https://framboisemood.files.wordpress.com/2013/04/fashion-zoo-animals13.jpg" />
<img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals9.jpg" />
</div>
CSS
.photoset > img:not(:first-child) {
display: none;
}
JavaScript
$(document).ready(function() {
$('.photoset').each(function(){
$(this).data('counter', 0);
});
var showCurrent = function(photoset) {
$items = photoset.find('img');
var counter = photoset.data('counter');
var numItems = $items.length;
var itemToShow = Math.abs(counter % numItems);
$items.fadeOut();
$items.eq(itemToShow).fadeIn();
};
$('.photoset').on('click', function(e) {
e.stopPropagation();
var photoset = $(this);
var pWidth = photoset.innerWidth();
var pOffset = photoset.offset();
var x = e.pageX - pOffset.left;
if (pWidth / 2 > x) {
photoset.data('counter', photoset.data('counter') - 1);
showCurrent(photoset);
} else {
photoset.data('counter', photoset.data('counter') + 1);
showCurrent(photoset);
}
});
});
and I want the images to overlap. When I click an image, the next one appears first on the bottom and then it appears in place of the first image.
How can I solve this issue? Thanks in advance.
Since 2 elements can't occupy the same position unless they're positioned to do so, I absolutely placed the other image above the previous one, and when the previous one disappears, I removed the absolute positioning.
Fiddle:
https://jsfiddle.net/qu1Lxjo1/
CSS:
.photoset {
position: relative;
}
.photoset img {
position: relative;
top: 0px;
left: 0pxx
}
JS:
$items.fadeOut();
$items.eq(itemToShow).fadeIn({done: function() {
$(this).css('position','relative')
}}).css('position', 'absolute');
};

Slideshow using Jquery, images do not fit window

I am trying to make a slideshow using jquery, I am a rooky in this code and am only familiar with css and html (though I am unsure how to position things in css). I want to create my slideshow and followed this template however I don't know how to change aspects of it, I tried messing around with it however no luck. My images are much bigger than the slide window created, I want to fit the image to the window, since now only a portion of the image is shown, which doesn't look very good.
So I was wondering how I could fit the complete image in that slidewindow (not a portion)
Here is what I have as html:
<div id="slideshow">
<div id="slideshowWindow">
<div class="slide">
<img src="Images/DSC_0419 copy.JPG" />
</div>
<div class="slide">
<img src="Images/DSC_1019 copy.JPG" />
</div>
<div class="slide">
<img src="Images/DSC_2975.JPG" />
</div>
</div>
</div>
My CSS:
#slideshow #slideshowWindow {
width:1000px;
height:700px;
margin:0;
padding:0;
position:relative;
overflow:hidden;
}
#slideshow #slideshowWindow .slide {
margin:0;
padding:0;
width:1000px;
height:700px;
float:left;
position:relative;
}
And this is my Jquery script:
<script type="text/javascript">
$(document).ready(function() {
var currentPosition = 0;
var slideWidth = 1000;
var slides = $('.slide');
var numberOfSlides = slides.length;
var slideShowInterval;
var speed = 3000;
slideShowInterval = setInterval(changePosition, speed);
slides.wrapAll('<div id="slidesHolder"></div>')
slides.css({ 'float' : 'left' });
$('#slidesHolder').css('width', slideWidth * numberOfSlides);
function changePosition() {
if(currentPosition == numberOfSlides - 1) {
currentPosition = 0;
} else {
currentPosition++;
}
moveSlide();
}
function moveSlide() {
$('#slidesHolder')
.animate({'marginLeft' : slideWidth*(-currentPosition)});
}
});
</script>
Try ...
#slideshow #slideshowWindow .slide img {
height: 100%;
width: 100%;
}
As it is, the CSS above will stretch the images ... if they are sized proportionately, this works fine ...
However, if you might be dealing with some images that are portrait and some landscape, try setting only height or only width; then, add adjustments to center when needed.

Add scroll animation to list in jQuery

I have a list where if you click prev next it goes left and right as shown in this fiddle
HTML
<div>
<span id="prev">prev</span>
<ul id="scrolllist">
<li><img src="http://dummyimage.com/100x100/000000/fff"></li>
<li><img src="http://dummyimage.com/100x100/f33636/fff"></li>
<li><img src="http://dummyimage.com/100x100/0c5b9e/fff"></li>
<li><img src="http://dummyimage.com/100x100/0c9e0c/fff"></li>
</ul>
<span id="next">next</span>
</div>
CSS
div {
float: left;
width: 550px;
}
li {
float: left;
list-style-type: none;
margin: 0 5px;
}
#prev {
cursor: pointer;
float: left;
}
#next {
cursor: pointer;
float: right;
}
JS
$(function () {
$('#prev').click(function () {
var first = $('#scrolllist li:first-child');
$('#scrolllist li').parent().append(first).animate({ "left": "-=50px" }, "slow" );
});
$('#next').click(function () {
var last = $('#scrolllist li:last');
$('#scrolllist li').parent().prepend(last).animate({ "left": "+=50px" }, "slow" );
});
});
This works moves them across as expected however I want to scroll the list items across to get the affect of them going in the clicked direction similar to what can be seen in http://coolcarousels.frebsite.nl/c/58/
What do I need to do to get this working?
The trick to doing it right is to place the images in a hidden container div and then animate that container to the left or right as needed, cloning the first or last img in the list and then appending or prepending depending on the direction.
The img container div must be placed inside another div with an explicit height and width with overflow set to hidden. This prevents the wide img container from being visible to the user.
Here is the HTML:
<div>
<span id="prev">prev</span>
<div class="scroll-container">
<div class="img-container">
<img src="http://dummyimage.com/100x100/000000/fff">
<img src="http://dummyimage.com/100x100/f33636/fff">
<img src="http://dummyimage.com/100x100/0c5b9e/fff">
<img src="http://dummyimage.com/100x100/0c9e0c/fff">
</div>
</div>
<span id="next">next</span>
And the JavaScript:
$(function () {
$('#prev').click(function () {
if(!$('.img-container').is(':animated')) {
var first = $('.img-container img:first-child');
var firstClone = first.clone();
$('.img-container').append(firstClone);
$('.img-container').animate({ "left": "-=110px" }, "slow", function() {
first.remove();
$('.img-container').css("left", "0");
});
}
});
$('#next').click(function () {
if(!$('.img-container').is(':animated')) {
var last = $('.img-container img:last-child');
var lastClone = last.clone();
$('.img-container').css("left", "-110px");
$('.img-container').prepend(lastClone);
$('.img-container').animate({ "left": "0" }, "slow", function() {
last.remove();
});
}
});
});
Note the 'if not animated' check at the beginning of each function. This prevents the user from running the functions again before the animation has completed (which would cause weird errors).
Here is a modified version of your fiddle: http://jsfiddle.net/fJqKV/17/

Adding a CSS class to span tag when corresponding image is slide in

I have a two phase animation including a div full of images and to the right, a paragraph of 10 span sentences. The images are absolute, so they stack on top of each other and have a negative margin initially to hide the image, by overflow: hidden.
On phase 1 (when page loads and before user hovers over a span), the images are set at a 5 second interval per image to loop through the images in an infinite manner. This phase and it's interval will clear when the second phase happens, which is when you hover over a span tag, in which the corresponding image slides in to view.
I have phase 1 and phase 2 coded, but my question is: In phase 1, I have to implement it so that when it's animating through the images by default, the corresponding span tag has to have a CSS class just like when you hover over the span tag in phase 2.
Here is the code if anyone wants to fiddle around with it:
<!--begin:content-->
<div id="content">
<div id="pics">
<img src="ADD ANY IMAGE" id="defaultImg" alt="" />
<img src="ADD ANY IMAGE" id="hover_1_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_2_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_3_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_4_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_5_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_6_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_7_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_8_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_9_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_10_pic" alt="" />
</div>
<!--begin: homeText - block of span tags w/text referenced in jQuery -->
<div class="homeText">
<p>
<span id="hover_1" >evolve water.</span>
<span id="hover_2">stream the party.</span>
<br />
<span id="hover_3">let moms play.</span>
<span id="hover_4">play on big screens.</span>
<br />
<span id="hover_5">turn txt into sport.</span>
<span id="hover_6">have 18 wheels.</span>
<br />
<span id="hover_7">have chapters.</span>
<span id="hover_8">personify an issue.</span>
<br />
<span id="hover_9">transform neighborhoods.</span>
<br />
<span id="hover_10">become keepsakes</span>
</p>
</div>
</div><!--end content-->
CSS
#pics img {
height: 131px;
width: 334px;
position: absolute;
margin-left:-325px;
}
/* ADDED by ben sewards */
#pics {
height:179px;
width:335px;
position: relative;
overflow: hidden;
margin:0px;
padding-top:15px;
margin-left:49px;
float:left;
}
/* ADDED by ben sewards */
.homeText {
width:600px;
height:240px;
padding-left:15px;
padding-top: 10px;
overflow: hidden;
float:left;
}
.homeText p {
line-height: 115%;
font-family: #Adobe Fangsong Std R;
font-size: 2.6em;
font-weight:bolder;
color: #c0c0c0;
margin: 0px;
}
.homeText span:hover {
background-color:Lime;
color: White;
cursor: pointer;
}
.span-background-change {
background-color:Lime;
color: White;
}
JS Script
$('document').ready(function () {
slideIn('defaultImg');
timer = setInterval('slideInNext()', 5000);
functionHover();
});
var slideSpeed = 500;
var slideIn = function (id) {
$('#' + id).addClass('active').animate({ 'margin-left': '0px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true });
}
var slideOutCurrent = function () {
$('#pics img.active').removeClass('active').animate({ 'margin-left': '325px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true, 'complete': function () { $(this).css('margin-left', '-325px'); } });
}
var slideInNext = function () {
var curImage = $('#pics img.active');
var nextImage = curImage.next();
if (nextImage.length == 0) {
nextImage = $('#pics img:first');
}
slideOutCurrent();
slideIn(nextImage.attr('id'));
}
var queueToSlideIn = [];
var mouseOnTimer = null;
var mouseOffTimer = null;
var functionHover = function () {
$('.homeText span').hover(
//binding 2 handlers to hover event
function () { //when hovering over a span - mousenenter
clearTimeout(mouseOffTimer);
clearInterval(timer);
var thisId = $(this).attr('id');
mouseOnTimer = setTimeout(function () {
if (!$('#' + thisId + '_pic').hasClass('active')) {
addToQueue(thisId + '_pic');
}
}, 300);
},
function () { //when off of span - mouseleave
clearTimeout(mouseOnTimer);
mouseOffTimer = setTimeout(function () {
if (!$('#defaultImg').hasClass('active')) {
addToQueue('defaultImg');
}
}, 500);
}
);
$('.homeText span').click(function () {
//set current span on click
$span = $(this).attr('id');
//navigate to corresponding case study
var href = $('#' + $span + '_pic').attr('alt');
window.location.href = href;
});
}
var addToQueue = function (id) {
queueToSlideIn.push(id);
$('#pics').queue(function () { animateNext(); $(this).dequeue(); }).delay(slideSpeed);
}
var animateNext = function () {
if (queueToSlideIn.length > 0) {
var id = queueToSlideIn.shift();
slideOutCurrent();
slideIn(id);
}
};
Sorry if the indenting is messy.
Ben
I added anew class which is a duplicate of your hover class:
.homeText-hover {
background-color:Lime;
color: White;
cursor: pointer;
}
Then I added two line each to your SlideIn and slideOutCurrent functions:
var slideIn = function (id) {
var slId = id.split('_pic');
$('#' + slId[0]).addClass('homeText-hover');
$('#' + id).addClass('active').animate({ 'margin-left': '0px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true });
}
var slideOutCurrent = function () {
var slId = $('#pics img.active').attr('id').split('_pic');
$('#' + slId[0]).removeClass('homeText-hover');
$('#pics img.active').removeClass('active').animate({ 'margin-left': '325px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true, 'complete': function () { $(this).css('margin-left', '-325px'); } });
}
Your autoslide isn't working out in FF...
I like your solution, Ben. Another solution that uses the same principle of selecting identifying attributes would be to add a class, unique to each img-span pair, to each of the elements, so that each shares a specific class with its corresponding element.
Below is an explanation of the use of classes as flags, which I originally posted in a solution to a different question that has since been closed:
Classes as Flags
Adding a class to an element does not always mean that you are going to be giving it some new CSS styles. CSS is a language that USES CLASSES in order TO HELP identify elements to style a particular way; classes are NOT FOR THE SOLE PURPOSE of applying CSS to an element. Were this not the case, CSS would only be able to style elements through the use of classes, and not through the use of other selectors (IDs, parents, children, descendants, etc.).
Developers often use classes as "flags." Flags are a way of signaling something about a particular element without having to store that information in a variable. For example, imagine you have a list of elements and all the elements are styled exactly the same, via a CSS class. If a developer wanted to mark every other element in this list in a particular way (for some later use), without changing the style of the elements, he may choose to add a second class called "alternate" to the elements.
You can add as many classes as you want to an element and it is totally accepted coding style to add multiple classes that do not have any associated styles (provided that such classes are for some other use -scripting, etc.).
Added this snippet of code to my slideInNext function for desired results:
if (nextImage.attr('id') != "defaultImg") {
//add class to corresponding span tag of current image
var spanId = nextImage.attr('id');
//corresponing span of next image
spanId = spanId.substring(0, spanId.length - 4);
$('#' + spanId).addClass('span-background-change');
}
I just used the substring method in javascript to pull apart the images attribute id and place it in a local variable to represent the span id.

Categories