Yujun Wu
Yujun Wu

Reputation: 3012

Get wrong value of css property in Firefox using jquery css()

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

Upvotes: 0

Views: 1154

Answers (2)

Bogdan
Bogdan

Reputation: 44526

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

Upvotes: 0

Ozerich
Ozerich

Reputation: 2000

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

Upvotes: 1

Related Questions