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

JavaScript

Adam Duffield
Adam Duffield
30,494 Points

JS Fade In/Out text

Hey All,

The absolute bane of my life is javascript no matter how many classes I just can't get along with it that well and I'm struggling for something for my portfolio. Basically I want random quotes to appear every 5 to 10 seconds by fading in & out. I've got the quotes and got the 5 seconds part nailed but I dont get how I can assign a fading in or out function to the div that is putting out the quotes.

I think the current code is irrelevant hence why i've not posted it on. All i need is a function that can fade in or out and to be able to assign it to my div so that it fades in & out every so many seconds.

4 Answers

Is this what you're looking for (using jQuery)?

Adam Duffield
Adam Duffield
30,494 Points

I reckon I could nail it with jQuery yeah but I'm after doing it the hard way through javascript to broaden my knowledge of JS.

James Barnett
James Barnett
39,199 Points

4th result on Google for the term fade vanilla javascript

function fadeOut(id, speed) {
    var s = document.getElementById(id).style;
    s.opacity = 1;
    (function fade() {(s.opacity-=.1)<.1?s.display="none":setTimeout(fade,speed)})();
}
Adam Duffield
Adam Duffield
30,494 Points

I appreciate the effort guys thankyou, but I've found and tried plenty of these snippets myself but the problem is I don't know how to apply that snippet of code to the div the contains them. If you get what I mean? I understand a lot of the syntax for JS and can get a good idea of whats happening its just applying it to the element, where do i need to stick the ID & the speed?

James Barnett
James Barnett
39,199 Points

Check out this working example, if you are still confused how to integrate it into your code, you'll need to post your code for more specific help.