Creating Image slider using only jQuery - javascript

I'm trying to create an image slider using Jquery.
What I have is a main div with 3 sub divs with images.
Take a look at this fiddle. FIDDLE
Ok now i got the design just the way I want it. What is missing is the functionality.
When i hover over the div or the images, I want it to act like a clockwise slider.
This may look a bit confusing. Take a look at this demo. This is what i want.
DEMO
This is what i want.The right div gets filled with the middle image src , the middle div gets the left div src. The left div get an new src from an array of images i have defined. Currently i can only change one image div at a time.
However I don't want to use any more plugins. Only Jquery plugin. A CSS only solution would be the best but I do not think it will be possible.
JQUERY
$('.maindiv img').mouseover(function () {
var image = this;
loop = setInterval(function () {
if (i < images.length - 1) {
i++;
$(image).attr('src', images[i]);
} else {
i = 0;
$(image).attr('src', images[i]);
}
}, 1500);
EDIT: I managed to get one part of this working. CHECK THIS.Just need to add fade effect Now the problem is after the images in the array end the first images dont loop back... Had not thought of this before.Does Anybody know how i can get over this issue?

Mabye something like this:
jQuery(document).ready(function () {
var images = [];
var loop;
var i = 0;
images[0] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ1GfA01TRDgrh-c5xWzrwSuiapiZ6b-yzDoS5JpmeVoB0ZCA87";
images[1] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQSyUWiS4UUhdP1Xz81I_sFG6QNAyxN7KLGLI0-RjroNcZ5-HLiw";
images[2] = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT_E_OgC6RiyFxKtw03NeWyelfRgJ3Ax3SnZZrufNkUe0nX3pjQ";
$('img', '.maindiv').mouseover(function () {
//Get divs inside main div and reverse them, so right is first
var divs = $($('div','.maindiv').get().reverse());
//Set up loop
loop = setInterval(function(){
divs.each(function(key, div){
if (divs[key+1])
{
//All divs gets image src from previous div > img
$('img', div).attr('src', $('img', $(divs[key+1])).attr('src'));
}
else
{
//This is left div
if (images && images[i])
{
//If picture url not in array then add it
if ($.inArray($('img', div).attr('src'), images) == -1)
{
images.push($('img', div).attr('src'));
}
$('img', div).attr('src', images[i]);
i++;
if (i>= images.length) i = 0;
}
}
});
}, 1500);
}).mouseout(function(){
clearInterval(loop);
});
});
Fiddle

Related

JSFiddle Slider code not working in browser

I'm a little lost. I have used this JSFiddle code regarding a solution to my problem. http://jsfiddle.net/f8d1js04/2/ (thank you MartinWebb) - and the question(for context) is posed here; Add Fade Effect in Slideshow (Javascript) - MartinWebb's solution is towards the bottom.
Essentially I am rendering a slider onto the page. Now when I put random image links into the imgArray on the JSFiddle, it behaves perfectly. However, when I do it on my page and in my files (in the dom), after the last image, there is a gap - time w/ no image showing, and then it continues to run. How do I get rid of this momentary gap?
Also any ideas on what could be causing this to happen on the browser instead of the JSFiddle?
Sincerely thank you for any help & assistance!
var curIndex = 0,
imgDuration = 3000,
slider = document.getElementById("slider"),
slides = slider.childNodes; //get a hook on all child elements, this is live so anything we add will get listed
imgArray = [
'http://placehold.it/300x200',
'http://placehold.it/200x100',
'http://placehold.it/400x300'];
//
// Dynamically add each image frame into the dom;
//
function buildSlideShow(arr) {
for (i = 0; i < arr.length; i++) {
var img = document.createElement('img');
img.src = arr[i];
slider.appendChild(img);
}
// note the slides reference will now contain the images so we can
access them
}
//
// Our slideshow function, we can call this and it flips the image instantly, once it is called it will roll
// our images at given interval [imgDuration];
//
function slideShow() {
function fadeIn(e) {
e.className = "fadeIn";
};
function fadeOut(e) {
e.className = "";
};
// first we start the existing image fading out;
fadeOut(slides[curIndex]);
// then we start the next image fading in, making sure if we are at the end we restart!
curIndex++;
if (curIndex == slides.length) {
curIndex = 0;
}
fadeIn(slides[curIndex]);
// now we are done we recall this function with a timer, simple.
setTimeout(function () {
slideShow();
}, imgDuration);
};
// first build the slider, then start it rolling!
buildSlideShow(imgArray);
slideShow();

How can I animate a recently created DOM element in the same function?

I'm working to create an image gallery where the images will be composed by progressively fading in layers one on top of the other to form the final image.
I have many such layers so instead of loading them into many different <img> elements all at once (which would slow load time) I want to start off with a single <img id="base"> and then progressively add image elements with the jQuery .after() method, assign them the relevant sources and fade them in with a delay.
The problem is that I can't attach animations to the newly created elements because (I'm assuming) they don't exist yet within the same function. Here is my code:
HTML
<div id="gallery">
<img id="base" src="image-1.jpg">
</div>
CSS
#base {
opacity: 0;
}
.layers {
position: absolute;
top: 0;
left: 0;
opacity: 0;
}
JavaScript
$(document).ready(function () {
$("#base").animate({opacity: 1}, 300); //fade in base
for (var i = 1; i <= numberOfLayers; i++, gap += 300) {
// create a new element
$("#base").after("<img class='layers' src='" + imgName + ".png'>");
// fade that new element in
$("#gallery").children().eq(i).delay(gap).animate({opacity: '1'}, 300);
}
}
Please note that I've altered my actual code to illustrate this better. I'm fairly new at JavaScript but I'm a quick learner so I'd appreciate if you could tell me what I'm doing wrong and what solution I should pursue.
EDIT: I've included my code inside your JSFiddle (all you need to do is add the library-X.jpg images) : http://jsfiddle.net/pgoevx03/
I've tried to replicate the intent of the code in a cleaner/more flexible way. Please let me know if I can do anything else to help.
I'm not saying this is the best way to do it, but it should be easy enough to understand and use.
The code is untested, but should work just fine. The comments should help you out if there's any compilation error.
Note that I removed the first image in the gallery (with ID "base") from the HTML file. It will be appended the same way as the rest.
// Array storing all the images to append to the gallery
var galleryImages = [
"image-1.jpg",
"image-2.jpg",
"image-3.jpg",
"image-4.jpg",
"image-5.jpg",
"image-6.jpg",
"image-7.jpg",
"image-8.jpg",
"image-9.jpg",
"image-10.jpg"
];
// Index of the image about to be appended
var imgIndex = -1;
var baseID = "base";
$(document).ready(function() {
// Start appending images
appendAllImages();
});
// Append the images, one at a time, at the end of the gallery
function appendAllImages() {
//Move to the next image
imgIndex++;
//We've reached the last image: stop appending
if (imgIndex >= galleryImages.length) return;
//Create image object
var img = $("<img>", {
src: galleryImages[imgIndex],
});
if (imgIndex === 0) { // It's the base!
//Give the base ID to the first image
img.attr("id", baseID);
//Append the image object
$("#gallery").append(img);
} else { // It's a layer!
//Give the base ID to the first image
img.attr("class", "layers");
//Append the image object
$("#" + baseID).after(img);
}
//Fade in the image appended; append the next image once it's done fading in
img.animate({
opacity: 1,
}, 300, appendAllImages);
}

adding fade to change background with javascript

I have the following code for changing a divs background image with jquery, i need help to add a fade to the code so the image change with some effect
this is the code
jQuery(window).load(function(){
var images = ['blured/1.jpg','blured/2.jpg'];
var i = 0;
var timeoutVar;
function changeBackground() {
clearTimeout(timeoutVar); // just to be sure it will run only once at a time
jQuery('#maincont').css('background-image', function() {
if (i >= images.length) {
i=0;
}
return 'url(' + images[i++] + ')';
});
// call the setTimeout every time to repeat the function
timeoutVar = setTimeout(changeBackground, 6000);
}
// Call it on the first time and it will repeat
changeBackground();
});
Any help will be great!
i need to just change the background image, without fading the inside divs, this is the html
<div class="maincont" id="maincont">
<div class="containersrch">
<h1 class="lagro">some title</h1>
<div class="joinus">
<span>JOIN</span>
</div>
</div>
Maybe this is what you want?
$(function(){
var imgId = $('#maincont'), imgCount = 1, imgLast = 2;
setInterval(function(){
imgId.fadeOut('slow', function(){
if(++imgCount > imgLast)imgCount = 1;
imgId.css('background', "url('blured/"+imgCount+".jpg')");
imgId.fadeIn('slow');
});
}, 6000);
});
Now you can have multiple images, just change imgLast to the last number and make sure they have the correct URLs in your blured folder. Of course, the code above assumes you are using .jpg. I actually recommend the lossless compression of .png, but it won't matter if it's the image was taken as a .jpg.

Simple loop for images

I'm trying to build a simple image slider (but using a fade effect). Every two seconds, the image should change to another image. At the end, it should call repeat_sponsor() again, to start over, so it becomes a loop.
I've written this (highly ineffective) code for 5 images. Turns out I'm going to need it for around 50 images. My editor just freezes when I add too much code.
I've tried using while-loops, but I just can't figure it out how to do this the right way.
Anyone who can help me with this?
function repeat_sponsor()
{
$("#sponsor2").hide();
$("#sponsor3").hide();
$("#sponsor4").hide();
$("#sponsor5").fadeOut("slow");
$("#sponsor1").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor2").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor3").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor4").fadeIn("slow", function() {
setTimeout(function(){$("#sponsor5").fadeIn("slow", ...
(function (){
var cnt = 50; //set to the last one...
var max=50;
function show() {
$("#sponsor" + cnt).fadeOut("slow"); //if you want the fadeout to be done before showing next, put the following code in the complete callback
cnt++;
if(cnt>max) {
cnt=1;
}
$("#sponsor" + cnt).fadeIn("slow");
window.setTimeout(show, 2000);
}
show();
})();
But the real issue is the fact you are loading tons of images from the start. You will be better off changing it so you only have a small subset of images and change the source.
You should use some sort of for loop and a class for hiding the images. and add a max value that if checks out resets c & i
var i=0;
var c=1;
function repeat_sponsor()
{
$("#sponsor"+i).fadeOut("slow");
$(".sponsers").hide()
$("#sponsor"+c).fadeIn("slow", function() {
window.setTimeout(repeat_sponsor(), 3000);
}
i++;
c++;
}
Just run a function every two seconds with setInterval and appropriately target your different sponsor divs:
var i = 1;
var max = 50;
setInterval(function() {
// Could target all other sponsor images with a class "sponsor"
$('.sponsor').fadeOut();
// Execute code on the target
$("#sponsor" + i).fadeIn();
if (i === max) {
i = 0;
}
i++;
}, 2000);

jQuery fadein and fadeout simulaneously

I currently use the following to fade images on my site:
$(document).ready(function() {
$('ul.image-switch li').mouseover(function(e) {
if (e.target.nodeName.toLowerCase() == 'a') return;
var image_src = $('a', this).data('image');
var img = $('.image-container img');
if (img.attr('src') != image_src) { // only do the fade if other image is selected
img.fadeOut(200, function() { // fadeout current image
img.attr('src', image_src).fadeIn(200); // load and fadein new image
});
}
});
});​
An example of this in action is at http://www.sehkelly.com/#news.
As you can see, the current image must fade out before the new one fades in.
I'd like the action to be simulaneous. Please -- does anyone know how I can achieve this?
Many thanks.
EDIT: Clueless novice. Code examples very much appreciated.
Create a new img element on top of the actual one, then fadeIn this new image. You'll need a bit of css to put the new image on top of the old one.
In no way you can do that with only one img element.
if (img.attr('src') != image_src) { // only do the fade if other image is selected
img.after(
$('<img />').attr('src', image_src).fadeIn(200)
);
img.fadeOut(200);
}
You would too want to wait for the new image to be loaded before starting fades. (checkout jQuery doc for the right function for that, and fade the images in the load callback).
Here's an implementation of Ulflander's idea, since the code posted is not complete http://jsfiddle.net/8nBqD/1/
The trick is to absolutely position the second image on top of the one you're fading out
HTML
<img id='pic1' src="http://periodictable.com/Samples/009.3b/s7.JPG" />
<img id='pic2' src="http://icons.iconarchive.com/icons/vargas21/aquave-metal/256/Sample-icon.png" />
CSS
#pic2 {
position: absolute;
display: none;
}​
JS
// Fade out the image, and replace it with the new one after the fade is over
$("#pic1").fadeOut(500, function() { // fadeout current image
this.src = 'http://icons.iconarchive.com/icons/vargas21/aquave-metal/256/Sample-icon.png';
$(this).show();
});
// Fade in the new image placing it on top of the original one
$("#pic2").offset($("#pic1").offset()).fadeIn(500, function(){
// Hide it since we are showing the original image with the new src
$(this).hide();
});
We could even write a plugin to make this easy to reuse
(function($) {
$.fn.imageFader = function(newSrc, seconds) {
$(this).each(function() {
var $img = $(this);
$img.fadeOut(seconds, function() {
this.src = newSrc;
$img.show();
});
var $tempImg = $('<img src="'+newSrc+'" style="position:absolute;display:none;" />').appendTo('body');
$tempImg.offset($img.offset()).fadeIn(seconds, function(){
$tempImg.remove();
});
});
};
})(jQuery);
And use it like http://jsfiddle.net/8nBqD/5/
$('img').imageFader('picture.png', 1000);

Categories

Resources