Phinet Phinet - 27 days ago 8
jQuery Question

Using em's in jQuery Script

I'm working on a website and I'm trying to make every measurement to be in em's, but but the script I repurposed from an old project I can't seem to get working with em's, it only seems to work with pixels.

$(window).scroll(function(){
$("#nav").css("top",Math.max(0,96-$(this).scrollTop()));
});


Here's a demo of what it does:

http://jsfiddle.net/hwRSF/1/

If anyone can help and show me what I need to do it would be greatly appreciated!

Answer Source

because scrollTop() returns in pixels, you will need to convert it into em values based on your base size.

For this particular question, it looks like your base size is 16, so you just need to divide the pixels by 16.

your navigation css:

#nav {
 ...
 top: 6em; /* 96 / 16 = 6*/
 ...
}

jquery:

$('#nav').css("top",Math.max(0,(96 - $(this).scrollTop())/16) + "em");

example fiddle: http://jsfiddle.net/hwRSF/3/