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
Aurelio Decock
14,607 PointsDifference between .on and .bind
Hello, I'm into designing and developing a few years before I joined the treehouse community. So I already got some designs and projects finished, It seemed a good time to set up a portfolio website for me.
For my portfolio I wanted to do something with the opacity while scrolling, I found this code on the web:
var fadeStart=100 // 100px scroll or less will equiv to 1 opacity
,fadeUntil=200 // 200px scroll or more will equiv to 0 opacity
,fading = $('#fading')
;
$(window).bind('scroll', function(){
var offset = $(document).scrollTop()
,opacity=0
;
if( offset<=fadeStart ){
opacity=1;
}else if( offset<=fadeUntil ){
opacity=1-offset/fadeUntil;
}
fading.css('opacity',opacity).html(opacity);
});
Can anyone tell me why I would use .bind instead of .on?
And in general what is happening in this .bind function? I don't seem to get what the opacity is doing here since it is not declared as a variable or anything like that. The only thing I can think of is opacity 0 = invisible and opacity 1 = 100% visible but i'm not too sure how this exactly works.
EDIT: I noticed how the opacity is declared as a var, must have overseen it.
Jeff Everhart
21,732 PointsThe difference involves how and when the event handlers are attached. Bind requires that the DOM element be present at the time the bind is called. The 'on' handler on the other hand will let you attach an event handler to a DOM element that is dynamically produced by attaching it to a previously existing element but having it act on any DOM element. For these reasons, 'on' is a better and more flexible option in almost all cases.
On another note, jQuery documentation recommends using 'on' instead of 'bind' as of 1.7, which was quite some time ago.
Cheers, JE
Aurelio Decock
14,607 PointsAurelio Decock
14,607 PointsI managed to figure it out myself, people who wants to know how I did it, this is my code: