2
votes

As stated in the question.

As I need to dynamically add elements into a container, I need to get the height and the width of the container in javascript. It works perfectly until I use media query in CSS to support mobile devices.

The container has fixed height and width in px, but when it got to mobile devices, it is too big and I want it to take 100% height of the devices.

html,body{
    width:100%;
    height:100%;
}
.container-div{
    width:500px;
    height:500px;
}
@media (max-width: 500px){
    .container-div{
        width:100%;
    }
}
@media (max-height: 500px){
    .container-div{
        height:100%;
    }
}

Then, in javascript:

console.log ($(".container-div").height());
console.log ($(".container-div").width());

It works fine when the media-query is not trigger. However, when the screen is getting small and trigger the media-query, the function always return 100. (This is the percentage I have set in CSS. I have tested that it return 90 when I changed to 90% in CSS.)

The container-div is put directly under body. Anybody know what's the problem and have an idea to solve it?

P.S. Reply to answers / comments:

  1. I am using Safari and chrome on mobile for the testing. This happens on both Apple's product and Android.
  2. I am loading the command in $(document).ready()
1
I tried your code on Mozilla 17.0.10. Your code is working fine here. I checked mobile view pressing ctrl + shift + m in mozilla - kundan Karn
Thanks, added PS above. I am using Chrome and Safari on Android and Apple system respectively. - cytsunny

1 Answers

0
votes

Could be a bug. However, since the container should take the dimensions of the entire viewport, did you try to fall back on $(window).height() ?