cusejuice
cusejuice

Reputation: 10691

jQuery window resize prepend

Having a problem with window resize. What I'm trying to do is check whether the window is less than 600 pixels, then prepend a div (.inner) to the body. On resize, I want to check the window width and if it's greater than 600 pixels, put the div (inner) back in its place.

HTML

<body>
  <div class="outer">
     <div class="inner">
     </div>
  </div>

JS

var windowWidth = $(window).width();

checkWidth();

function checkWidth(){
    if(windowWidth > 600){
    $('.outer').append($('.inner'));
    console.log('back in place');
  } else {
    $('body').prepend($('.inner'));
        console.log('prepend');
  }
}
$(window).resize(function() {
  checkWidth();
}).trigger('resize');

Upvotes: 0

Views: 489

Answers (1)

BenM
BenM

Reputation: 53238

You need to retrieve the width inside of your function. Otherwise it will always contain the value before the resize.

$(checkWidth);
$(window).resize(checkWidth).trigger('resize');

function checkWidth()
{
    var window_width = $(window).width();

    if(window_width > 600)
    {
        $('.outer').append($('.inner'));
        console.log('back in place');
    } 
    else 
    {
        $('body').prepend($('.inner'));
        console.log('prepend');
    }
}

Upvotes: 3

Related Questions