eylay
eylay

Reputation: 2160

Divs aren't aware of screen resizing

First div is a category and the second div contains some photos.

I wanted to do something that when user clicks on an image the first div move 0.7 of the screen width to right and all images in second div disappear, so I wrote:

$(document).ready(function() {
  $("img").click(function() {
    var my_width = screen.width * 0.7;
    $(".second_div").find("img").hide();
    $(".first_div").css({
      "transform": "translate(" + my_width + "px,0px)",
      "-webkit-transform": "translate(" + my_width + "px,0px)",
      "-ms-transform": "translate(" + my_width + ",0px)"
    });
  });
});
.first_div {
  transition-duration: 2s;
}
<div class="first_div col-md-1">
  //some code
</div>
<div class="second_div col-md-11>
           //some codes
</div>

When its full screen it works right, but when I resize the window and try again the first div won't be located at where it supposed to (0.7 Of screen width) What's wrong?

Upvotes: 5

Views: 103

Answers (2)

thedarklord47
thedarklord47

Reputation: 3302

for window width I would use the following:

var my_width = document.documentElement.clientWidth * 0.7;

this is the same (cross-browser compatible) solution used by jQuery's $.width()

For more info on different methods of getting width, see this link.

Upvotes: 3

Pabs123
Pabs123

Reputation: 3435

Try using the window's inner width instead of the screen width, so that it's relative to the size of the viewport. replace

var my_width = screen.width * 0.7 ;

with:

var my_width = window.innerWidth * 0.7 ;

See an example here:

http://codepen.io/anon/pen/jWWEKO

Upvotes: 2

Related Questions