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
Aleksandr Vinogradov
12,113 PointsMy personal JavaScript and jquery function project.
Its my personal thing just got started with and i cant figure it out! I am working on a function. The purpose of the function is store an array of selectors which later will run in a for loop that creates functions with these selectors. That function runs a code when the user has scrolled to an element. Lets say when a person will reach a div with class about it will fade in. I have an error that i have been trying to fix for an hour now. I need help!
The error is following:
Uncaught TypeError: Cannot read property 'top' of undefinedindex.html:157 (anonymous function)jquery.min.js:3 m.event.dispatchjquery.min.js:3 m.event.add.r.handle
I understand the problem... I am not sure how to solve it..
The problem is that the function inside the for loop doesn't understand selected[i]
Please help!
var selected=[];
function selecting(select) {
selected.push(select);
}
selecting("#about");
for(i=0; i<selected.length; i+=1){
console.log(selected[i]);
$( selected[i] ).hide();
$(window).scroll(function() {
var hT = $(selected[i]).offset().top,
hH = $(selected[i]).outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
console.log('you have scrolled to the'+ selected[i]);
}
})
}
Aleksandr Vinogradov
12,113 PointsTHANK YOU!!! @miguelcastro2
miguelcastro2
Courses Plus Student 6,573 Pointsmiguelcastro2
Courses Plus Student 6,573 PointsWhat's happening is you are trying to access a member of the selected array which does not exist. The offending line:
var hT = $(selected[i]).offset().top,I would change:
You can refactor your code by creating a reusable variable for your selected item: