简体   繁体   中英

Conditionally Fixed DIV Based on Window Size

I'm trying to write a script that will fix a DIV if the screen is a certain width. This is what I have so far, but the logic is not correct and I'm not sure how to write it.

var controller = new ScrollMagic();

var w = $(window).width();
if(w >= 500) {
    var sidebar = new ScrollScene()
        .triggerHook("0")
        .setPin("#sidebar-pin")
        .addTo(controller);   
}
$(window).on('resize',function(){
    if(w < 500) {
            controller.removePin("#sidebar-pin",true);
    } else {
    var sidebar = new ScrollScene()
        .triggerHook("0")
        .setPin("#sidebar-pin")
        .addTo(controller); 
  }
});

http://jsfiddle.net/gtowle/jxoewzoo/

The logic I'm aiming for is:

  1. On page load, if the the window width is greater than 500, do A. If not, do nothing.
  2. On window resize, if the window width becomes less than 500, do B, and if it becomes greater than 640, do A.

I think my problem is that I'm not sure how to trigger #2 once the window is resized.

The first problem is that you only calculated the window's width once (on page load).
It isn't updated, once you resized.
That's why the whole resize logic doesn't have any effect.

Another mistake you made was calling the removePin method on the controller.
It's a scene method.

Lastly your logic would create a new scene every time instead of updating the existing one.

So here's how you properly achieve your desired logic:

var controller = new ScrollMagic();

var sidebar = new ScrollScene({triggerHook: 0})
    .addTo(controller);

// page load
if($(window).width() >= 500) {
    sidebar.setPin("#sidebar-pin");
}

// resize
$(window).on('resize',function(){
    var w = $(window).width();
    if(w < 500) {
        sidebar.removePin("#sidebar-pin",true);
    } else if (w >= 640) {
        sidebar.setPin("#sidebar-pin");
    }
});

And here's your fiddle: http://jsfiddle.net/jxoewzoo/1/

hope this helps,
J

Instead use css mediaqueries for something like this.

The js code for onscroll:

var otherwise = true
if(w < 500) {
        Do B;
        otherwise = false;
}
if(w > 640) {
        Do A;
        otherwise = false;
}
If(otherwise) {
     var sidebar = new ScrollScene()
    .triggerHook("0")
    .setPin("#sidebar-pin")
    .addTo(controller); 
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM