How to use jQuery's ScrollTop function with em valuse?

Issue

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?

Solution

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());
  }
});

Answered By – James Bruckner

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published