Javascript resize function

I run into a problem with javascript that resize elements according screen size. I would like to translate this code with same functionality to css simple class.

$(window).resize(function(){ // On resize
   $('item2').css({'height':(($(window).height()))+'px'});
});

I have tried

.test2 {
    height: 100%;
}

But doesn`t work - if I delete script part elements are not the desired with (full screen height).

Problem with script is that it implement the style to markup, which can`t be changed with media queries unless using !important...

Upvotes: 0

Views: 107

Answers (2)

n1kkou
n1kkou

Reputation: 3142

For you to have an element with height equal to screen height, you either have to set the position:fixed to that element and add height:100%, or, if you want to keep the document flow, you also need to set the document height to 100%, also all the parents of the child element have to be 100% height.

The easiest way is obviously the first approach, but that option will pull your element from the natural document flow.

.test2{
    position:fixed;
    top:0;
    left:0;
    height:100%;
    z-index:2;
}

$(window).resize(function(){
     $('item2').addClass('test2);
});

Keep in mind that this function is running on every resize event, which is performance costly.

To understand the issue, you can check this explanation about debouncing: https://davidwalsh.name/javascript-debounce-function

Upvotes: 1

Mamun
Mamun

Reputation: 68923

If item2 is a class then you need to add . in the selector.

$(window).resize(function(){ // On resize
  //$('.item2').css({'height':(($(window).height()))+'px'});
  $('.item2').height($(window).height());
});

Upvotes: 2

Related Questions