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

Javascript run function in js file on page load

I have a home page with a series of links that go to a different page with articles. The articles all have id's and I would normally use anchor links to jump to the correct article (so website.com/articles.html#myarticle). However the page I'm going to has a horizontal layout and uses iScroll js for the scrolling so I need to use the iscroll function to get it to go to the right article (anchor links don't work). So I'm wondering if there's a way that when you click on the link on the home page that I can have it open the article page and then run the special iscroll function (which is inside a linked .js file) to get to that specific id tag? Something like this: HOME PAGE -->click on link -->takes you to article page -->runs function from JS file (which will scroll to the id using iScroll) referencing the specific id that was clicked

Not sure this makes sense to anyone but any guesses might point me in the right direction! Thanks!

1 Answer

I suppose you can do something like this:

var articleID = window.location.hash;
myScroll.scrollToElement('#'+articleID, 100); //you have to call it on your current instance of iscroll

This will take the hash (in your case myarticle) and it pass it to iScroll's method scrollToElement(). Your article should have the same ID myarticle.

Thanks, that's pretty much what I did and got it to work. if(window.location.hash) { var articleID = (location.hash).replace('#',''); scroll_to_id_function(articleID); }

Then the scroll_to_id_function() has the iscroll method that uses the articleID variable. I'm actually using iScroll's goToPage method, not the scrollToElement, but it works pretty much the same way. So the articleID variable serves as the "page" number for iScroll. This is all in a js file that is loaded at the end of my articles page, so I left the links on the home page to have anchor links to the article id's. It seems to be working!