0

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
user3552129
  • 55
  • 1
  • 6

3 Answers3

5

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());
  }
});
Community
  • 1
  • 1
James Bruckner
  • 909
  • 7
  • 10
1

I'm afraid you don't. ScrollTop uses pixels:

ref: https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop

There is no way to easily translate between absolute pixels to relative ems.

Mister Epic
  • 16,295
  • 13
  • 76
  • 147
1

The following code may help as given on [1]: http://jsfiddle.net/davidThomas/nEnNC/2/

function px2em(elem) {
var W = window,
    D = document;
if (!elem || elem.parentNode.tagName.toLowerCase() == 'body') {
    return false;
}
else {
    var parentFontSize = parseInt(W.getComputedStyle(elem.parentNode, null).fontSize, 10),
        elemFontSize = parseInt(W.getComputedStyle(elem, null).fontSize, 10);

    var pxInEms = Math.floor((elemFontSize / parentFontSize) * 100) / 100;
    elem.style.fontSize = pxInEms + 'em';
}
}

Also you can refer this question jQuery/JavaScript: convert pixels to em in a easy way

TylerH
  • 20,799
  • 66
  • 75
  • 101
Monika
  • 135
  • 1
  • 12