0

With the html:

<a class="jslider-pointer" href="#" style="left: 50%;"></a>

I used jquery api css() to get the value of left property:

$('.jslider-pointer').first().css('left')

It worked well in chrome, which returned 50%. But it didn't work in Firefox. It returned 150px in Firefox.

Does anyone know why it happened and how could I get the right value in Firefox(a method working across different browsers)?

Thanks

Spudley
  • 166,037
  • 39
  • 233
  • 307
Yujun Wu
  • 2,992
  • 11
  • 40
  • 56

2 Answers2

1

returns px value

$('.jslider-pointer').offset().left

In other way you can calculate yourself

parseInt($('.jslider-pointer').css('left')) / $('.jslider-pointer').parent().width() * 100;

There is good plugin for you cross-browser issue jQuery dimensions

Ozerich
  • 2,000
  • 1
  • 18
  • 25
  • I want it to return percentage value. You mean I have to calculate by myself? But in chrome it just return the percentage value using css() – Yujun Wu Sep 22 '12 at 21:06
  • 1
    left property is relative to the first parent being none static ... offset method give you the offset relative to the document. As a consequence, this will not always work as expected `:/` – Stphane Sep 22 '12 at 21:39
0

According to this other post Retrieving percentage CSS values (in firefox) this is a know bug. Based on the fiddle in that post's answer I've made a jQuery plugin which should get rid of your problem:

(function($) {
    $.fn.cssFix = function(property) {
        var el = this[0], value;

        if (el.currentStyle)
            value = el.currentStyle[property];
        else if (window.getComputedStyle)
            value = document.defaultView.getComputedStyle(el,null).getPropertyValue(property);

        return value;
    }
})(jQuery);

Usage:

$('.jslider-pointer').first().cssFix('left');

Here's a fiddle that uses this plugin and works on both Chrome and Firefox, and returns the value as it was defined in the css rule: either % or px.

EDIT: Tested in Internet Explorer and it works there as well

Community
  • 1
  • 1
Bogdan
  • 43,166
  • 12
  • 128
  • 129
  • Actually, the right behavior per spec is unclear. There are some who are pushing for it to be the used value (150px) and some who want it to be the computed value (50%). But the key is that `.css()` does NOT return the specified value. It returns whatever `getComputedStyle().left` returns. Which is somewhat underdefined at the moment. – Boris Zbarsky Sep 24 '12 at 18:41