jQuery CSS functions. Part 1 – offset()

What are jQuery CSS functions?

Well these are function which help you modify different CSS properties with JavaScript. You know you can do that in “pure” evangelistic JS, but normally every library comes with its own bunch of functions that do the job. In fact in jQuery the things are little bit more complicated because the returned value of those CSS modifiers is yet again a object of the element you modify, which is the same object as this you’ve selected with one of the selectors in jQuery.

This is extremely useful when it comes to chains and you chain several functions using the dot operator. Thus you call more and more functions for every selector and perform a modifier every time you call them.

When it comes to the slogan of jQuery which promise us to do the same things as “pure” JavaScript, but with less code, well this chaining is the prove.

One of the main CSS helper selectors is the offset. It can be defined by at least two different ways. Once you may have the offset of an element from the beginning of the page, where this should be point (0, 0), and in other way you may want to have the offset from the containing element of the selected one.

Actually in jQuery you can use the .offset() method that especially for absolute positioned elements gives you the offset from the top left corner of the page.

Where they can be useful?

The offset of an element, which is absolutely positioned is useful when you make some JS based animations or sliders (which in fact is animation) or whatever.

$.offset()

The offset function returns an array with two values “left” and “top”. Normally that gives the offset in pixels.

Some tips and tricks

Because the JavaScript is extremely powerful you get a bonus when referencing the $.offset() method.

Instead of:

var offset = $('#element').offset();
console.log(offset['left']);
console.log(offset['top']);

you can write:

console.log($('#element').offset()['left']);

which is really groovy.

3 thoughts on “jQuery CSS functions. Part 1 – offset()

  1. because offset() is also a json object you can also leave out the brackets and quotes and write the above example like this:
    console.log($(‘#element’).offset().left);

Leave a Reply

Your email address will not be published. Required fields are marked *