Hide A DIV if screen is narrower than 1024px

≯℡__Kan透↙ 提交于 2019-11-29 04:37:19

OLD ANSWER USING JQUERY:

//the function to hide the div
function hideDiv(){

    if ($(window).width() < 1024) {

            $("#floatdiv").fadeOut("slow");

    }else{

        $("#floatdiv").fadeIn("slow");

    }

}

//run on document load and on window resize
$(document).ready(function () {

    //on load
    hideDiv();

    //on resize
    $(window).resize(function(){
        hideDiv();
    });

});

EDIT: Please note that now there is much more cross browser support for css3 media queries it would be much more effective to use those rather than javascript.

USING CSS.

/* always assume on smaller screen first */

#floatdiv {
    display:none;
}

/* if screen size gets wider than 1024 */

@media screen and (min-width:1024px){
    #floatdiv {
        display:block;
    }
}

Note that in most modern browsers you can also run media queries in javascript using window.matchMedia

if(window.matchMedia("(min-width:1024px)").matches){
    console.log("window is greater than 1024px wide");
}

you need to set the screen element:

var screen = $(window)

for example:

$(document).ready(function () {

    var screen = $(window)    

    if (screen.width < 1024) {
        $("#floatdiv").hide();
    }
    else {

        $("#floatdiv").show();
    }

});
Coops

Media queries for the win

How do I make a div not display, if the browser window is at a certain width?

@media all and (max-width: 1024px) { /* Change Width Here */
  div.class_name {
     display: none;
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!