James
James

Reputation: 133

Automatically resize window with JQuery

To extend the responsiveness to my site, I've added the below JQuery to handle situations when the screen width is below 1300px. It almost works perfectly, however - it doesn't take into account the screen size updating, I.e. when screen is less than 1300 it does apply the appends, however if I then adjust the screen to above 1300px it will keep the conditional changes.

$(window).on('resize',function() {
    if ($(this).width() < 1300) {
        $("#id").appendTo("#div");
        $("#id").appendTo("#div");
    }
}); 

Upvotes: 0

Views: 345

Answers (2)

Kevin Doveton
Kevin Doveton

Reputation: 396

media queries would be the better solution, but if you wanted to keep what you already have use the following jquery to remove the item once it reaches full size again.

var isAppended = false; // place this at the top of your file
$(window).on('resize',function(){
  var width = $(this).width();
  // dont append unless it doesnt exist 
  // and size smaller than break size
  if (!isAppended && width < 1300) {
    $("#id").appendTo("#div");
    $("#id2").appendTo("#div");
    isAppended = true;
  }
  else if (isAppended && width >= 1300) {
    $("#id").remove();
    $("#id2").remove();
    isAppended = false;
});

in order to use a media query to solve the problem

HTML

<div id="id1"></div>

CSS

#id1 {
  display: none;
}

@media (max-width: 1300px) {
  #id1 {
    display: block;
  }
}

Upvotes: 2

Aditya_kr
Aditya_kr

Reputation: 175

use media query for responsiveness on different screen sizes, its easy to handle than jquery

Upvotes: 1

Related Questions