Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jackson Monk
4,527 PointsjQuery is being weird
Here is my code:
comDivs = document.getElementsByClassName('comDiv');
for (let y = 0; y < comDivs.length; y ++) {
$(comDivs[y]).delay(4000).fadeOut(400);
if (y + 1 != comDivs.length) {
if (comDivs[y].style.display == 'none') {
$(comDivs[y + 1]).delay(500).fadeIn(400);
}
}
}
I have two comDivs, one is hidden. In this loop I attempt to fade out the visible one and smoothly fade the invisible one in. When I do this code outside the loop, it works fine, but inside it only fades the first one out, then stops. Why doesn't it fade the second one in?
3 Answers
Zhaopeng Wang
Full Stack JavaScript Techdegree Graduate 32,210 PointsTry this:
comDivs = document.getElementsByClassName('comDiv');
for (let y = 0; y < comDivs.length; y ++) {
$(comDivs[y]).delay(4000).fadeOut(400, function () {
if (y + 1 != comDivs.length) {
$(comDivs[y + 1]).delay(500).fadeIn(400);
}
});
}
You may visit https://stackoverflow.com/questions/7539199/jquery-fadein-one-element-after-fadeout-the-previous-div for more examples. I think you have similar questions.
Zhaopeng Wang
Full Stack JavaScript Techdegree Graduate 32,210 Points//First thing, under your for loop, you have this code
$(comDivs[y]).delay(4000).fadeOut(400);
/* The .fadeOut() method animates the opacity of the matched elements.
Once the opacity reaches 0, the display style property is set to none. And, you call delay(4000) before fadeOut.
Means that you let the program wait for 4 seconds then call fadeOut()
Under your chrome Development tools, if you call comDivs[y].style.display, during the 4 seconds of delay, you may find that it will return "" instead of "none" during delay(4000). After 4 seconds, comDivs[y].style.display='none'
*/
// Therefore, you second if statement will stop the program, since during the 4 seconds delay,
if (comDivs[y].style.display == 'none') {
//will return false
$(comDivs[y + 1]).delay(500).fadeIn(400);// will not be called
Jackson Monk
4,527 PointsSo do I get rid of the delay? What's my move here?
Jackson Monk
4,527 PointsJackson Monk
4,527 PointsI will try this. Thanks!