简体   繁体   中英

Why does this jQuery code works only once?

I have this short jQuery code to make the picture disappear when the window is resized. For some reason, after it disappears, it doesn't appear again. Here is the code:

$(document).ready(function(){
    $(window).resize(function(){

        if($(window).width() < 700) {
            $("#side-pic").css("display","none");


        } else if($(window).width() >= 700){

            $("#side-pic").css("display","show");
        }

    });
    });

Also if by any chance you know if there is a way to make picture move under a certain div in my code, I'll be glad to hear it! Thank you guys in advance!

There is no display property such as display: show . Try using $("#side-pic").css("display","block"); instead.

Another Alternative would be hide/show:

$(document).ready(function(){
    $(window).resize(function(){

        if($(window).width() < 700) {
             $("#side-pic").hide();
        } 
        else if($(window).width() >= 700) {
             $("#side-pic").show();
        }

    });
});

That's because the "show" is not a valid display value. https://developer.mozilla.org/en-US/docs/Web/CSS/display

Also, why the else if , isn't an else good enough?
Or rather a reusable CSS class and jQuery's toggleClass() Method:

 jQuery( $ => { $(window).on('resize', function() { $("#side-pic").toggleClass("is-hidden", $(this).width() < 700); }); });
 .is-hidden {display: none;}
 <div id="side-pic">SIDE PIC</div> <script src="//code.jquery.com/jquery-3.1.0.js"></script>

You can also write a code Like following

$(document).ready(function(){
    $(window).resize(function(){

        if($(window).width() < 700) {
            $("#side-pic").hide();


        } else if($(window).width() >= 700){

            $("#side-pic").show();
        }

    });
});

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