Perkin5
Perkin5

Reputation: 399

dynamic resizing with jquery

I've seen another reference to this but I can't understand the response. I am trying to change the height of a page element (#maincontent) dynamically as the window is re-sized.

This is my code:

$(function() {
   if($(window).resize()){
      var h1 = $(window).height();
      var h2 = $('#maincontent').height();
      if (h2<h1){
          $('#maincontent').css('height',h1);
      }
   }
});

It doesn't work without a page refresh and I can't understand why not. Where have I gone wrong?

Upvotes: 1

Views: 211

Answers (5)

Roko C. Buljan
Roko C. Buljan

Reputation: 206689

It's because on page load no resize will trigger.

var h2 = $('#maincontent').height();

function setSize(){         // wrap you necessary code inside a function
   var h1 = $(window).height();       
   if (h2<h1){
      $('#maincontent').css({height: h1 });
   }
}
setSize();                 // call at page load

$(window).resize(function(){
  setSize();               // and on window resize.
});

Upvotes: 1

gaurang171
gaurang171

Reputation: 9090

$(function() {
    $(window).resize(function(e){

        var h1 = $(window).height();
        var h2 = $('#maincontent').height();
        if (h2<h1){
        $('#maincontent').css('height',h1);
        }

    })
 });

you should not check if but pass function for resize event

Upvotes: 1

Lowkase
Lowkase

Reputation: 5699

Your not capturing the window resize event properly:

   $(window).resize(function () {

      var h1 = $(window).height();
      var h2 = $('#maincontent').height();
      if (h2<h1){
          $('#maincontent').css('height',h1);
      }

   });

Upvotes: 2

Austin
Austin

Reputation: 6034

This is because window.resize() takes a function as its argument

EX.

    $(function () {
        $(window).resize(function () {
            // your code here
        });
    });

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382474

The resize function doesn't work like this. It takes a function as argument :

$(function(){
    $(window).resize(function() {
       // do things when the window is resized
    });
});

Most jquery functions take like this a callback that is called when the event (here 'resize') is sent.

Upvotes: 1

Related Questions