0

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...

1
  • 2
    item2 is an tag name ? Commented Apr 20, 2017 at 8:04

2 Answers 2

2

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());
});
Sign up to request clarification or add additional context in comments.

3 Comments

I see I forgot . but it doesnt solve the problem of replacing the script with pure css. Is it possible to replace $(window).resize(function(){ // On resize $('.item2').css({'height':(($(window).height()))+'px'}); }); Only with css ?
Please add the html.
Try the updated code by using jQuerys height() method.
1

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

1 Comment

I used min-height:100%;. with fixed position as you mention and it works. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.