jQuery Animation, Chaining, .each() and .animate() (or fadeIn() and fadeOut()) - javascript

I'm having a bit of a trouble trying to figure this out today, i want to make 5 items inside my DOM (which is listed under the same attribute element, $('.elements')) fade in and out, and after reading up a bit on the API i thought .each() would be a fabulous idea to implement a fade in and fade out showcase gallery.
However, i'm currently using:
$('.elements').each(function() {
$(this).fadeIn(2000).delay(200).fadeOut(2000).show();
})
but everything gets faded in and out at once.
How do i do a sequential effect where everything is chained together and it starts from the first item in the list (a.k.a - $('elements').eq(0)?) down to the last one, and then restarts again?
Do i really need a while loop to do this in javascript/jquery? I was hoping there would be a similar function that i could chain for jQuery to perform to reduce load and filesize.
Also, is there a way to restrict the images from overflowing out from my div?

(function loop() {
$('.elements').each(function() {
var $self = $(this);
$self.parent().queue(function (n) {
$self.fadeIn(2000).delay(200).fadeOut(2000, n);
});
}).parent().promise().done(loop);
}());
demo: http://jsfiddle.net/uWGVN/2/
updated to have it looping without end.
2nd update: a different, probably more readable, approach:
(function fade(idx) {
var $elements = $('.elements');
$elements.eq(idx).fadeIn(2000).delay(200).fadeOut(2000, function () {
fade(idx + 1 < $elements.length ? idx + 1 : 0);
});
}(0));
​demo: http://jsfiddle.net/uWGVN/3/

You can add a callback
offical doc :
('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
and call the same function with i++ et $('.elements').eq(i)
http://jsfiddle.net/dFnNL/

For your overflowing , style it with CSS:
div.(class) { position:relative; overflow:hidden; }

Beautiful way :
(function hideNext(jq){
jq.eq(0).hide("slow", function(){
(jq=jq.slice(1)).length && hideNext(jq);
});
})($('a'))
last first :
(function hideNext(jq){
jq.eq(jq.length-1).hide("slow", function(){
(jq=jq.slice(0,length-1)).length && hideNext(jq);
});
})($('a'))

Related

Get child div of existing div using anchors next element without ID or class using JQuery

As you can see below $(nextDiv + ' > div').eq(i).fadeIn('slow'); does not work as it seems to be malformed. nextDiv is on inspection the div below the anchor, how do I achieve getting the two divs that sit inside it?
HTML:
Sub Click
<div>
<div>I want this to fade in on the click</div>
<div>Followed by this etc.</div>
</div>
Javascript:
function subClick(myAnchor)
{
var nextDiv = $(myAnchor).next();
function showDiv(i) {
if (i > 2) return;
setTimeout(function () {
$(nextDiv + ' > div').eq(i).fadeIn('slow');
showDiv(++i);
}, 50);
}
showDiv(0);
}
You are trying to concatenate a string with jQuery, that won't provide a valid selector. The concatenation would provide something like "[object Object] > div" which doesn't select any elements in your code.
Instead, get the div children using children() method on the jQuery nextDiv object.
nextDiv.children('div').eq(i).fadeIn('slow');
If there are only two divs then you can reduce the code using delay() method.
function subClick(myAnchor) {
var nextDivs = $(myAnchor).next().children();
// if you want to do the animation after the first then
// use the below code, where second animation initializing within
// the first animation success callback, which also provides a 50ms
// delay for second animation(avoid .delay(50) if you dont nedd that delay)
// nextDivs.eq(0).fadeIn('slow', function() {
// nextDivs.eq(1).delay(50).fadeIn('slow');
// });
// in case you just want to provide a 50ms delay
// between animation then use, your code does this
nextDivs.eq(0).fadeIn('slow');
nextDivs.eq(1).delay(50).fadeIn('slow');
}
var nextDiv = $(myAnchor).next(); then nextDiv is an object not a selector. If you want to access its div children use this:
nextDiv.children('div').eq(i).fadeIn('slow');

how to repeat same Javascript code over multiple html elements

Note: Changed code so that images and texts are links.
Basically, I have 3 pictures all with the same class, different ID. I have a javascript code which I want to apply to all three pictures, except, the code needs to be SLIGHTLY different depending on the picture. Here is the html:
<div class=column1of4>
<img src="images/actual.jpg" id="first">
<div id="firsttext" class="spanlink"><p>lots of text</p></div>
</div>
<div class=column1of4>
<img src="images/fake.jpg" id="second">
<div id="moretext" class="spanlink"><p>more text</p></div>
</div>
<div class=column1of4>
<img src="images/real.jpg" id="eighth">
<div id="evenmoretext" class="spanlink"><p>even more text</p></div>
</div>
Here is the Javascript for the id="firsttext":
$('#firstextt').hide();
$('#first, #firsttext').hover(function(){
//in
$('#firsttext').show();
},function(){
//out
$('#firsttext').hide();
});
So when a user hovers over #first, #firsttext will appear. Then, I want it so that when a user hovers over #second, #moretext should appear, etc.
I've done programming in Python, I created a sudo code and basically it is this.
text = [#firsttext, #moretext, #evenmoretext]
picture = [#first, #second, #eighth]
for number in range.len(text) //over here, basically find out how many elements are in text
$('text[number]').hide();
$('text[number], picture[number]').hover(function(){
//in
$('text[number]').show();
},function(){
//out
$('text[number]').hide();
});
The syntax is probably way off, but that's just the sudo code. Can anyone help me make the actual Javascript code for it?
try this
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink").show();
});
Why not
$('.spanlink').hide();
$('.column1of4').hover(
function() {
// in
$(this).children('.spanlink').show();
},
function() {
// out
$(this).children('.spanlink').hide();
}
);
It doesn't even need the ids.
You can do it :
$('.column1of4').click(function(){
$(this); // the current object
$(this).children('img'); // img in the current object
});
or a loop :
$('.column1of4').each(function(){
...
});
Dont use Id as $('#id') for multiple events, use a .class or an [attribute] do this.
If you're using jQuery, this is quite easy to accomplish:
$('.column1of4 .spanlink').hide();
$('.column1of4 img').mouseenter(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').show();
});
$('.column1of4 img').mouseleave(function(e){
e.stopPropagation();
$(this).parent().find('.spanlink').hide();
});
Depending on your markup structure, you could use DOM traversing functions like .filter(), .find(), .next() to get to your selected node.
$(".column1of4").hover(function(){
$(".spanlink").hide();
$(this).find(".spanlink, img").show();
});
So, the way you would do this, given your html would look like:
$('.column1of4').on('mouseenter mouseleave', 'img, .spanlink', function(ev) {
$(ev.delegateTarget).find('.spanlink').toggle(ev.type === 'mouseenter');
}).find('.spanlink').hide();
But building on what you have:
var text = ['#firsttext', '#moretext', '#evenmoretext'];
var picture = ['#first', '#second', '#third'];
This is a traditional loop using a closure (it's better to define the function outside of the loop, but I'm going to leave it there for this):
// You could also do var length = text.length and replace the "3"
for ( var i = 0; i < 3; ++i ) {
// create a closure so that i isn't incremented when the event happens.
(function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(',')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
})(i);
}
And the following is using $.each to iterate over the group.
$.each(text, function(i) {
$(text[i]).hide();
$([text[i], picture[i]].join(', ')).hover(function() {
$(text[i]).show();
}, function() {
$(text[i]).hide();
});
});
Here's a fiddle with all three versions. Just uncomment the one you want to test and give it a go.
I moved the image inside the div and used this code, a working example:
$('.column1of4').each(function(){
$('div', $(this)).each(function(){
$(this).hover(
function(){
//in
$('img', $(this)).show();
},
function(){
//out
$('img', $(this)).hide();
});
});
});
The general idea is 1) use a selector that isn't an ID so I can iterate over several elements without worrying if future elements will be added later 2) locate the div to hide/show based on location relational to $(this) (will only work if you repeat this structure in your markup) 3) move the image tag inside the div (if you don't, then the hover gets a little spazzy because the positioned is changed when the image is shown, therefore affecting whether the cursor is inside the div or not.
EDIT
Updated fiddle for additional requirements (see comments).

jQuery slide changing with index and fadeout -- jumpiness

I am working on a jQuery slideshow plugin. One of my methods involves switching back and forth between pictures. I have been pretty successful in creating it, here is an isolated case with the code thus far for the particular method:
var images = $("#simpleslides").children("img");
$(".slideButtons ul li").on("click", "a", function() {
var anchorIndex = $(this).parent().index();
var $activeSlide = $("#simpleslides img:visible");
var $targetSlide = $(images[anchorIndex]);
if($activeSlide.attr("src") == $targetSlide.attr("src") || $targetSlide.is(":animated")) {
return false;
} else {
$activeSlide.css({ "z-index" : 0 });
$targetSlide.css({ "z-index" : 1 });
$targetSlide.stop().fadeIn("slow", function() {
$activeSlide.hide();
});
}
});
Here is a fiddle to see it in working action: http://jsfiddle.net/ase3E/
For the most part, this works as you would expect it to. When a user clicks on the corresponding number, it fades in the picture.
However, I am running into some jumpiness and occasionally a complete hide of the slides when I am clicking around quickly. If you play with the fiddle, you will see what I am referring to Try clicking around on each image to see.
I have adopted stop which I thought would fix the problem but has not. I have put the hide method after the fadeIn callback, but that has also not helped the situation.
What am I doing wrong here??
LIVE DEMO :)
var images = $("#simpleslides").find("img");
$(".slideButtons ul").on("click", "li", function(e) {
e.preventDefault();
var i = $(this).index();
images.eq(i).stop().fadeTo(500,1).siblings('img').fadeTo(500,0);
});

Simplify my menu animation code

I've got a bunch of 'project' divs that I want to expand when they're clicked on. If there's already a project open, I want to hide it before I slide out the new one. I also want to stop clicks on an already open project from closing and then opening it again.
Here's an example of what I mean (warning - wrote the code in the browser):
$('.projects').click(function() {
var clicked_project = $(this);
if (clicked_project.is(':visible')) {
clicked_project.height(10).slideUp();
return;
}
var visible_projects = $('.projects:visible');
if (visible_projects.size() > 0) {
visible_projects.height(10).slideUp(function() {
clicked_project.slideDown();
});
} else {
clicked_project.slideDown();
}
});
Really, my big issue is with the second part - it sucks that I have to use that if/else - I should just be able to make the callback run instantly if there aren't any visible_projects.
I would think this would be a pretty common task, and I'm sure there's a simplification I'm missing. Any suggestions appreciated!
slideToggle?
$('.projects').click(function() {
var siblings = $(this).siblings('.projects:visible');
siblings.slideUp(400);
$(this).delay(siblings.length ? 400 : 0).slideToggle();
});
Used a delay rather than a callback because the callback is called once per matched item. This would lead to multiple toggles if multiple items were visible.
Like this?
$(".projects")
.click(function () {
var a = $(this);
if (a.is(":visible")) return a.height(10)
.slideUp(), void 0;
var b = $(".projects:visible");
b.size() > 0 ? b.height(10)
.slideUp(function () {
a.slideDown()
}) : a.slideDown()
})

jQuery Closures, Loops and Events

I have a question similar to the one here: Event handlers inside a Javascript loop - need a closure? but I'm using jQuery and the solution given seems to fire the event when it's bound rather than on click.
Here's my code:
for(var i in DisplayGlobals.Indicators)
{
var div = d.createElement("div");
div.style.width = "100%";
td.appendChild(div);
for(var j = 0;j<3;j++)
{
var test = j;
if(DisplayGlobals.Indicators[i][j].length > 0)
{
var img = d.createElement("img");
jQuery(img).attr({
src : DisplayGlobals.Indicators[i][j],
alt : i,
className: "IndicatorImage"
}).click(
function(indGroup,indValue){
jQuery(".IndicatorImage").removeClass("active");
_this.Indicator.TrueImage = DisplayGlobals.Indicators[indGroup][indValue];
_this.Indicator.FalseImage = DisplayGlobals.IndicatorsSpecial["BlankSmall"];
jQuery(this).addClass("active");
}(i,j)
);
div.appendChild(img);
}
}
}
I've tried a couple of different ways without success...
The original problem was that _this.Indicator.TrueImage was always the last value because I was using the loop counters rather than parameters to choose the right image.
You're missing a function. The .click function needs a function as a parameter so you need to do this:
.click(
function(indGroup,indValue)
{
return function()
{
jQuery(".IndicatorImage").removeClass("active");
_this.Indicator.TrueImage = DisplayGlobals.Indicators[indGroup][indValue];
_this.Indicator.FalseImage = DisplayGlobals.IndicatorsSpecial["BlankSmall"];
jQuery(this).addClass("active");
}
}(i,j);
);
Solution by Greg is still valid, but you can do it without creating additional closure now, by utilizing eventData parameter of jQuery click method (or bind or any other event-binding method, for that matter).
.click({indGroup: i, indValue : j}, function(event) {
alert(event.data.indGroup);
alert(event.data.indValue);
...
});
Looks much simpler and probably more efficient (one less closure per iteration).
Documentation for bind method has description and some examples on event data.
Nikita's answer works fine as long as you are using jQuery 1.4.3 and later. For versions previous to this (back to 1.0) you will have to use bind as follows:
.bind('click', {indGroup: i, indValue : j}, function(event) {
alert(event.data.indGroup);
alert(event.data.indValue);
...
});
Hope this helps anyone else still using 1.4.2 (like me)

Categories

Resources