Reputation: 23
if ($(body).scrollTop() > 120px)
{
document.getElementByID("head").ID = "headfixed"
}
this doesn't work, and I'm not surprised, but nowhere I look helps me with what I want to do. Can I get some help on this? thanks in advance.
Upvotes: 0
Views: 37125
Reputation: 2972
Question: why are you using a combination of element selectors with jQuery, and "getElementById"? Here's how I'd re-write your function.... You need to put this if statement in a function that occurs when something happens. In this case, it' when the window scrolls.
$(window).scroll(function () {
var $this = $(this),
$head = $('#head');
if ($this.scrollTop() > 120) {
$head.addClass('fixed_header');
} else {
$head.removeClass('fixed_header');
}
});
Does this make sense? also, scrollTop doesn't go off of pixels, but it's an integer. By the way, only window and this can go in the parens without quotes... body, html, etc.... need quotes around them when being selected.
Upvotes: 9
Reputation: 1
you must make sure that 'if condition' is in the scroll function.
function scroll() {
if ($(body).scrollTop() > 120px)
{
document.getElementByID("head").ID = "headfixed"
}
}
Upvotes: -1
Reputation: 10638
I think scroll top returns an integer value, so your comparison value should be 120 and not 120px.
EDIT:
Additionally, do you get a syntax error for 120px, since it is not wrapped in quotes? When I tested in jsfiddle, I got the following error in Firebug:
identifier starts immediately after numeric literal
Upvotes: 1
Reputation: 13565
I think the value that you are looking for is .offset().top
. That will return the current position of $elem
relative to the top of the document.
// below: the offset of the body tag to the top of the page
$("body").offset().top
// below: the offset of the element with the id #head to the top of the page
$("#head").offset().top
Upvotes: 2