Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.css(): Firefox don't return 'auto' values

I'm setting top or bottom and left or right values to a few elements. When i'm trying to access this values with Firefox (16.0.2), i get a wrong value for top (a specific value instead of auto)

CSS

div {
    bottom:200px;
    left:0px;
    top:auto;
    right:auto;
}

JS

$(function(){
    var top = $('div').css('top');
    alert(top);
});​

You can try it here: http://jsfiddle.net/UEyxD/2/ (works well in Chrome/Safari)

Any ideas how to prevent this? I want to get

like image 620
Slevin Avatar asked Nov 19 '12 14:11

Slevin


2 Answers

I also had this annoying problem.

Some browsers return the computed position if the element is visible at the moment. The trick is to hide it, read the css and then make it visible again (if was not already hidden).

I wrote a convenient function that takes care of this and will return auto in Firefox.

jsFiddle

var getCss = function($elem, prop) {
        var wasVisible = $elem.css('display') !== 'none';
        try {
            return $elem.hide().css(prop);
        } finally {
            if (wasVisible) $elem.show();
        }
    };


alert( getCss($('div'), 'top') );

The finally is just to bring visibility back to the element, just before the function returns.

You should use this function only for situations where you expect auto to be returned.

like image 175
Jose Rui Santos Avatar answered Oct 12 '22 11:10

Jose Rui Santos


You Can Get integer Value of top when you set 'auto' with below code:

$(function(){
    var top = $('div').offset().top;
    alert(top);
});​
  • offset Return Position Value When you Set To Auto
like image 35
Ahmad Ronagh Avatar answered Oct 12 '22 11:10

Ahmad Ronagh