سؤال

I am attempting my first "progressive enhancement" site and have a question about jQuery append and browser resizing. Basically, I have it set up so that the default site that is loaded is the mobile version and then I have a jQuery function to append desktop elements to the divs on the page if the browser width is a minimum of 1100px.

It works great but now I just need to tackle the resizing issues. Currently, if you resize the browser window below 1100px width, the elements that are appended to the divs do not disappear until you refresh the browser. I would like to make it so that if the browser window is resized below 1100px, the elements that were appended disappear without a refresh.

Could someone point me in the right direction? Thanks!

HTML:

<div id="section1">

</div>

Javascript:

if (window.matchMedia("(min-width: 1100px)").matches) {
    $("#section1").append("\
        <div class='placeholder'>\
            <img src='assets/site/desktop_placeholder.png' />\
        </div>\
    ");
}
هل كانت مفيدة؟

المحلول

I've been playing around with it a bit and I think I'm getting close. Let me know if there is a better way to do this or if you see any issues with this code. Thanks!

function appendElements() {
    //swap in desktop content
    if (window.matchMedia("(min-width: 1100px)").matches) {
        $("#section1").append("\
            <div class='placeholder'>\
                <img src='assets/site/desktop_placeholder.png' />\
            </div>\
        ");
    }
    }else{
        $("#section1").empty();
    }
}

if (window.matchMedia("(min-width: 1100px)").matches) {
    appendElements();
}

$(window).resize(function(){
    appendElements();    
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top