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

Smooth Scrolling to add a class, and then scroll away to remove said class, how do I make it work?

I'm working on a personal project, and when the user presses a certain link (I named it applyNow here) I want the page to smooth scroll to a certain div (contactForm = $('#contact-form')). For that I created this function:

function smoothScroll(target) { $('body').animate({scrollTop: $(target).offset().top}, 'slow'); return false;

}

And then added it to this event handler in jQuery

applyNow.click(function() { smoothScroll('#contact-form'); // if(document.body.scrollTop > $(document).offset().bottom) { contactForm.addClass('glowy'); // } });

I want the text of the div to be uhm....illuminated when the scrolling gets there. So far so good. But I also want the glowyness to disappear when I scroll away from it. I have failed miserably in trying to do that and I don't seem to be able to figure it out. I can't tie a removeClass method to a scrolling event, because it removes the class just as the dynamic scrolling is taking place.

Help?

2 Answers

You could include an if statement inside your event handler that checks if the top of your div is at the top of the screen whenever the scroll event occurs. If it is, add the class to make the text "glow", otherwise remove the class so the text does not glow anymore.

hope this helps!

It did, thanks ^_^!

Since the div is small and near the bottom of the page, the scroll top thing doesn't exactly work, but since the smooth scrolling ends at the bottom, I added an if statement to add the glow class every time said bottom is reached (and remove it when you scroll up). It's working quite well :D.