Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Adam Duffield
Adam Duffield
30,493 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,493 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,493 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.