简体   繁体   中英

jQuery - How to not execute a single line command

I am relatively new in web development, so not sure I am explaining myself with the right terms, but have come to this little issue in a small project of mine:

I have a navigation menu with functionality (mainly style related) added through a switch. When browsing the mobile version of the site, the elements inside the menu change differently and as that I want that some of the commands listed on the switch case to not be executed. Here's a simplified example in the code I have:

//main (desktop) site functionality
$(".nav").click(function(event) {

    var what = event.target.className;

    switch (what){
        case "item 1":
            if ($(".text1").css("display") == "none"){
                $(".text1").css("display", "block");

                //this below is the line I don't want it to execute when on mobile
                $(".item5").css("margin-top","196px");
            } else {
                $("text1").css("display", "none");
                $(".item5").css("margin-top","0");
            }
            break;
    });

    //This is the function I use to know you are browsing on a mobile,
    //where the main change inside the CSS media query is not displaying the "scroller"
    function checkif(){
        if ($(".scroller").css("display") == "none" ){
        $(".item5").insertAfter($(".item12"));
        if($(".text1").css("display") == "block"){
            $(".item5").css("margin-top","0");
        }
    }
});

This is simplified, the changes within cases are more than just a margin, I change color, text, display of multiple elements. As that I don't want it to just not execute the switch, just to read the properties of the checkif() function and execute those instead of the ones in the switch when overlapping (as in the margin). Thank you!

Seems like the key to your solution is to find whether the user is using a mobile device or not.

Let me suggest you another way to detect mobile device instead of your checkif() function.

 function isMobile(){ // Get device user agent string var userAgent = navigator.userAgent; // Regular expression to sniff user agent var regexp = /mobi/i; // Test if the regexp exists in the user agent string return regexp.test(userAgent); } console.log(isMobile()); 

More notes on this here .

Anyway, you should be doing what you need to do in CSS instead of JavaScript unless you have a good justification.

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