Imesh Chandrasiri
Imesh Chandrasiri

Reputation: 5679

css("position") returns undefined when window resize

I've got the following code to catch the browser resize event.

 window.onresize = function(){
 var style = $('#button-selection').position();
 if(style == "relative"){
 $("#button-section").css("position"," ");
 }else if(style == "fixed"){
    $("#button-section").css("position","relative");
 }              
 };


 window.onresize = function(){
            var style = $('#button-selection').css('position');
            if(style == "relative"){
                $("#button-section").css("position"," ");
            }else if(style == "fixed"){
                $("#button-section").css("position","relative");
            }               
        };

The style returns undefined. I'm running this when the document is ready. I tried using window ready but the result is the same. both the above methods return undefined!

Upvotes: 3

Views: 413

Answers (2)

Jai
Jai

Reputation: 74738

Change this:

var style = $('#button-selection').position();

to this:

var style = $('#button-selection').css('position');

.position() is used to get the coordinates of the element.

From the docs:

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.


Update:

Use $(window).resize() instead. i am having a test case scenario here: in this fiddle.

$(window).resize(function () {
  var style = $('button').css('position');
  if (style == "relative") {
    alert('relative');
  } else if (style == "fixed") {
    alert('fixed');
  }
});

Upvotes: 5

Bernat
Bernat

Reputation: 1556

jQuery docs say .position() is:

Description: Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

you should use:

 var style = $('#button-selection').css('position');

Upvotes: 1

Related Questions