Loop jQuery function with fadeIn - javascript

I'm using a simple jQuery function to create a small image slider:
function gridhover() {
$(".grid-item .slide-image").each(function(index) {
$(this).delay(400*index).fadeIn(300);
});
}
$( ".grid-item" ).hover(function() {
gridhover();
});
If the function plays once, it stops. Is there a way to loop the function? Check out my CodePen!

The idea here is that since you fadeIn something you must also fade it out and repeat the same process again and again
function gridhover() {
$(".grid-item .slide-image").each(function(index) {
$(this).delay(2000*index).fadeIn(300);
});
$(".grid-item .slide-image").each(function(index) {
$(this).delay(2000*index).fadeOut(300);
});
}
try this but with better timming

Based on this example I prepared this jsFiddle for you.
<div id="cycler">
<img class="active" src="image1.jpg" alt="My image" />
<img src="image2.jpg" alt="My image" />
...
</div>
What he does in his example is he picks the .active element and looks for it's next sibling to know which one to show next. If it does not exist, it means the current active is the last one, so he takes the first one again. Simple.
I took his function and applied it to the .hover(). And also set the myInterval variable as global so you can access it from the .hover() and it's callback function.
var milisecs = 1000;
var myInterval;
$("#cycler").hover(function(){
myInterval = setInterval(function(){cycleImages()}, milisecs);
}, function(){
clearInterval(myInterval);
});
...
Check out the jsFiddle for the whole thing.
Hope it helps.

Related

jQuery loop image fadeout/in with time interval

I have a jQuery function to fadeIn/Out images in a div. But when the function reaches last image, it gets stopped. Any way to get it in a loop, so that at the end of last image, it will start again from the first image.
here is the code
HTML:
<div id="homeimg">
<img src="image1.jpg" />
<img src="image2.jpg" />
<img src="image3.jpg" />
<img src="image4.jpg" />
</div>
jQuery:
$(document).ready(function(){
$('#homeimg img:first-child').addClass('activeimg');
setInterval('cycleMe()', 4000);
});
function cycleMe() {
$('.activeimg').next().css('z-index', 10);
$('.activeimg').next().fadeIn(1500);
$('.activeimg').fadeOut(1500, function(){
$(this).next().fadeIn(0);
$(this).next().addClass('activeimg');
$(this).css('z-index', 5).removeClass('activeimg');
});
}
Any possibilities?
First of all, you're passing the function in as a string, which is a no-no. I think you're over-complicating your code, and there are some jQuery efficiencies you can leverage.
First, I don't think it's necessary to modify the z-index of your images: the fading should handle all that. Secondly, you can chain jQuery calls (see below how fadeIn and addClass chained). Lastly, every time you do $('.activeimage'), jQuery has to scan the DOM again, which is inefficient. Best to do it once and cache the answer (whenever I store a jQuery object, I begin it with a dollar sign by convention, so I always know I'm dealing with a jQuery-wrapped object).
Here's how I would re-write this:
$(document).ready(function(){
$('#homeimg img:first-child').addClass('activeimg');
setInterval(cycleMe, 4000);
});
function cycleMe() {
var $active = $('#homeimg .activeimg');
var $next = $active.next('img');
if(!$next.length) $next = $('#homeimg img:first-child');
$active.fadeOut(1500, function(){
$(this).removeClass('activeimg');
$next.fadeIn().addClass('activeimg');
});
}
Working jsfiddle: http://jsfiddle.net/6MHDn/
You can also do this with simple array manipulation:
$(document).ready(function () {
$('#homeimg img:first-child').addClass('activeimg');
setInterval(cycleMe, 4000);
// get an array of your images
var arrImgs = $('#homeimg img');
function cycleMe() {
var currImg = arrImgs[0];
var nextImg = arrImgs[1];
// You can do this with simple array splicing and pushing
$(nextImg).css('z-index', 10);
$(nextImg).fadeIn(1500);
$(currImg).fadeOut(1500, function () {
$(nextImg).fadeIn(0);
$(this).css('z-index', 5);
// remove the first item from the array
arrImgs.splice(0,1);
// add it to the end of the array
arrImgs.push(currImg);
});
}
});
jsFiddle: http://jsfiddle.net/mori57/4FbVD/
Taking into consideration some of Ethan's comments, I also tried it this way:
http://jsfiddle.net/mori57/4FbVD/2/
$(document).ready(function () {
$('#homeimg img:first-child').addClass('activeimg');
setInterval(cycleMe, 4000);
// get an array of your images
var arrImgs = $('#homeimg img');
function cycleMe() {
var currImg = $(arrImgs[0]);
var nextImg = $(arrImgs[1]);
// You can do this with simple array splicing and pushing
nextImg.fadeIn(1500);
currImg.fadeOut(1500, function () {
currImg.removeClass('activeimg');
nextImg.fadeIn(0).addClass('activeimg');
// remove the first item from the array
arrImgs.splice(0,1);
// add it to the end of the array
arrImgs.push(currImg);
});
}
});
In my previous attempt, I was having to requery the DOM both for css change and fadeIn ... inefficient. Cache the jQuery object, /then/ do the manipulation, and sans-z-index as in Ethan's approach. I'd still rather not have to requery the DOM at all for each element inside an infinite loop. If I find a way around that, I'll post it as well.

JQuery pass HTML ID as parameter

Here is my code:
HTML
<img src"../MyPic_1" id="MyImg_1" onclick = "MyJQfunction($(this))">
<img src"../MyPic_2" id="MyImg_2" onclick = "MyJQfunction($(this))">
<img src"../MyPic_3" id="MyImg_3" onclick = "MyJQfunction($(this))">
JQUERY
<script>
function MyJQfunction(MyField)
{
MyField.hide();
}
</script>
As you can see I'm trying to send the HTML element to my JQ Function so it knows what to hide.
What am I doing wrong?
NOTE: This is just a simple example of what I really need to do, I just want to avoid including codes that you don't care about. Thanks!
You are using jquery so attach an event handler instead of using onclick
<img src="../MyPic_1" id="MyImg_1" class="myIMage">
<img src="../MyPic_2" id="MyImg_2" class="myIMage">
<img src="../MyPic_3" id="MyImg_3" class="myIMage">
and
$(function(){
$('.myIMage').on('click', MyJQFunction);
}
function MyJQFunction()
{
$(this).hide(); //here this represents the element clicked.
}
Or classic way; use Function.call to set the context for the function while invocation.
<img src"../MyPic_1" id="MyImg_1" onclick = "MyJQfunction.call(this)">
and
function MyJQFunction()
{
$(this).hide(); //and this here is now the clicked element.
}
Also in your code your image tag seems to be incorrect and MyJQfunction versus MyJQFunction has casing (note the casing of f) issue. Check your console for errors. Otherwise your code should work.
This is what I would do:
<img src="../MyPic_1" id="MyImg_1" class="image_to_hide"/>
<img src="../MyPic_2" id="MyImg_2" class="image_to_hide"/>
<img src="../MyPic_3" id="MyImg_3" class="image_to_hide"/>
...
<script>
$(".image_to_hide").click(function(){
$(this).hide();
});
</script>
You should wrap that on jquery function like this
function MyJQFunction(MyField)
{
$(MyField).hide();
}

Running continuous events after each other

I've been trying to make this for 2 days, I apologize I'm new to Javascript/Jquery and I'm in the learning process.
I'm trying to create a javascript when the page is loaded will have an image fade in and fade out and after the first image fades in and out then a second, third, etc. however many I need.
I know this is a newby question but I'm clearly not sure what to look for at this point. And I have been doing research and learning along the way, I just would like to have it sooner than I may be able to accomplish.
Any help is appreciated.
This is what I came up with which to me looks completely invalid, but seems to work:
<div class="splashbg1" style="display: none;"></div>
<div class="splashbg2" style="display: none;"></div>
<div class="splashbg3" style="display: none;"></div>
<div class="splashbg4" style="display: none;"></div>
<div class="splashbg5" style="display: none;"></div>
<script>
$(document).ready(function() {
$('.splashbg1').fadeIn(1300, function() {
$('.splashbg1').fadeOut(1300, function() {
$('.splashbg2').fadeIn(1300, function() {
$('.splashbg2').fadeOut(1300, function() {
$('.splashbg3').fadeIn(1300, function() {
$('.splashbg3').fadeOut(1300, function() {
$('.splashbg4').fadeIn(1300, function() {
$('.splashbg4').fadeOut(1300, function() {
$('.splashbg5').fadeIn(1300, function() {
});
});
});
});
});
});
});
});
});
});
</script>
example HTML:
<div id="images>
<img src="">
<img src="">
...
</div>
example Javascript:
function switchImage(){
$('#images img:visible').fadeOut(function(){
$(this).next().length ? $(this).next().fadeIn() : $('#images img').eq(0).fadeIn();
});
};
$('#images img').hide().eq(0).show(); // show only the first image
setInterval(switchImage, 2000); // loop through images every 2000 milliseconds
example: http://jsfiddle.net/ampersand/nhp2v/
You can use an array and a variable containing the current image, then fade them in and out. It depends on how your images are stored. If you have one <img> element with an ID of myImg, for example, you could do this:
var images = ['http://someurl.com/someimg.jpg', 'somethingelse.png', 'hello.gif'];
var currentImage = 0;
function next() {
$('#myImg').fadeOut(function() {
$('#myImg').prop('src', images[currentImage]).fadeIn(); // Set the image and fade in
currentImage++; // Get ready for the next image
});
}
next();
If you wanted it to wrap, you could do images[currentImage % images.length]. If there are a bunch of different images, you can do about the same thing, just keep the IDs of the images in images instead.
I wrote a quick function called sequence below. Make a list of the images you'd like to animate using jQuery selectors like this:
var list = [
$('first'),
$('second'),
$('third')
];
Then call the function below with something like this sequence( list, 200, function(){} );
var sequence = function( array, duration, callback ){
var list = array,
length = list.length,
i = 0,
duration = duration,
callback = callback;
function chainFade(){
if( i < length )
array[i].fadeIn( duration )
.fadeOut( duration, function(){
i++;
chainFade();
});
else
typeof callback == 'function' && callback();
}
chainFade();
};
I haven't tested it yet so let me know if you run into any bugs.

Javascript hide/show - more elegant way to do this?

I'm looking for a more elegant way to make a hide/show of divs using inline Javascript.
If you mouse over the orangish/yellow circle logos over the cars the tag should appear. When moused out they should disappear.
URL:
http://174.120.239.48/~peakperf/
<div class="second">
<div id="speech2" style="display: none">
<img src="<?php bloginfo('template_url'); ?>/images/speech2.png" width="334" height="50">
</div>
<a id="various2" href="#inline2,javascript:HideContent('speech1')" title="" onmouseover="HideContent('speech1'); return true;">
<img src="<?php bloginfo('template_url'); ?>/images/clicker.png" width="62" height="50" onmouseover="document.getElementById('speech2').style.display = 'block'" onmouseout="document.getElementById('speech2').style.display = 'none'">
</a>
</div>
Here's the pastebin of the code used:
http://pastebin.com/JsW6eJRZ
The more elegant solution is to utilize JQuery.
Once you include the library into a file, a div show is done using the following selector
$('#idOfDiv').show();
Or if there are no ids but rather classes
$('.ClassName').show();
Now instead of having onclick events in the html as you have right now, you just bind them in jquery in the ready() method like so:
$(document).ready(function()
{
$('#idOfDiv').bind('click', function()
{
//do work here in this anonymous callback function
});
});
All of this can be done in a external js file so that will significantly clean up your html code
and put all your javascript logic into one location.
EDIT:
Example applied to your situation
$(document).ready(function()
{
$('#various1').mouseover(function()
{
$('#speech1').show();
});
$('#various1').mouseout(function()
{
$('#speech1').hide();
});
});
If you get crafty and utilize a for loop then you could just append the number to the end of the string that represents the selectors like so
$(document).ready(function()
{
for(var i = 1; i < 7; i++)
{
$('#various' + i).mouseover(function()
{
$('#speech' + i).show();
});
$('#various' + i).mouseout(function()
{
$('#speech' + i).hide();
});
}
});
The mouseout and mouseover functions are just the explicit version of using like so
$('selector').bind('mouseover', function()
{
});
$('selector').bind('mouseout', function()
{
});
Have you looked into using jQuery for this? Also, why does the code need to be inlined?
I would recommend doing something like this: http://jsfiddle.net/4N9ym/2/
Note that I have things inverted here (you would probably want to animate in instead of animating out).

Is there a way to determine when 4 images have been loaded using JS?

I have 4 images on a page. I want to trigger a JS event once all 4 images are loaded. I of course can't be sure which order the images will be loaded in, so I can't trigger the event on the last image. One thought was to have a counter, but I can't think of the best way to check when that counter is equal to 4 as I don't like the idea of a setTimeout() checking every 200ms.
Any other ideas?
I'm using jQuery on the site, so I'm thinking that might be some help.
This is the image HTML code:
<img src="/images/hp_image-1.jpg" width="553" height="180" id="featureImg1" />
<img src="/images/hp_image-2.jpg" width="553" height="180" id="featureImg2" />
<img src="/images/hp_image-3.jpg" width="553" height="180" id="featureImg3" />
<img src="/images/hp_image-4.jpg" width="553" height="180" id="featureImg4" />
As regards Salty's example, it's best to use a closure to avoid global variables, like such:
$("img").load(function() {
var count = 0, numImages = $("img").size();
return function () {
if (++count === numImages) {
//All images have loaded
}
};
}());
[Edit]
As per jeroen's comment, I replaced the hardcoded value of 4 (count === 4) with the jQuery size function as to allow for more flexibility within the function.
count=0;
$("img").load(function() {
count++;
if(count==4) { //All images have loaded
//Do something!
}
});

Categories

Resources