How do I make this code work with em
values?
$(window).scroll(function() {
if ($(window).scrollTop() > 100) {
$('#scroller').css('top',$(window).scrollTop());
}
});
I want the 100 to be 10em, how can I do it?
As ems are different based on the font size of an element, I'd assume you would be referencing the body
font size.
Number(getComputedStyle(document.body, "").fontSize.match(/(\d*(\.\d*)?)px/)[1]);
That will give you the font size in pixels, which you can multiple by however many ems you want to use.
Source: Converting em to px in Javascript (and getting default font size)
Example:
// scroll top using 10em
var tenEms = Number(getComputedStyle(document.body, "").fontSize.match(/(\d*(\.\d*)?)px/)[1]) * 10;
$(window).scroll(function() {
if ($(window).scrollTop() > tenEms) {
$('#scroller').css('top',$(window).scrollTop());
}
});