Detecting when the page has scrolled
Our next task is to detect when the page has been scrolled and fix the element in place when that occurs. Detecting the scroll event is made easy for us by jQuery, as is setting the position
to fixed
, because there are simple jQuery methods we can call to do these exact things.
Engage Thrusters
Add the following code to the script file directly after the variables we initialized in the last task:
win.one("scroll", function () { fixedEl.css({ width: width, position: "fixed", top: Math.round(initialPos.top), left: Math.round(initialPos.left) }); });
Objective Complete - Mini Debriefing
We can use jQuery's one()
method to attach an event handler to the window
object that we stored in a variable. The one()
method will automatically unbind the event handler as soon as the event is detected for the first time, which is useful because we only need to set the element to position:fixed
once. In this example we are looking for...