简体   繁体   中英

Toggle behaviour based on screen width

The goal here is to make a page responsive and mobile friendly.

I show an invoice with all its details when on a desktop. But when the viewport is reduced, the details are hidden and can be toggled (hide/unhide) on clicking/tapping.

So I have a trigger and a target class.

$('.trigger').click(function(){
    $('.target').toggleClass('hide');
})

This works as expected if I add the hide class to target in my markup. But I cannot do that as they should appear unless the user views the page at a small screen. I can set display: none in the media queries but that hides target for good.

What property of the target element should I modify so that it hides itself when the screen size is reduced and I can toggle its view with the hide class?

This all depends on what you are doing:

You could use JavaScript to detect the width and add specfic classes on the toggle to display it.

$screenWidthCheck = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if ($screenWidthCheck > 1280) {
    $("#page-content").addClass('active');
}

You could then add an even to it.

$(window).resize(function() { 
    $screenWidthCheck = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    if ($screenWidthCheck > 1280) {
        $("#page-content").addClass('active');
    }
});

A Javascript solution would be to add a hook to load and resize event handlers that would check the screen width and add/remove the class accordingly.

$(window).on("load resize", function() {
    //Assuming you consider anything >= 1240 as desktop
    $('.target').toggleClass('hide', $(window).width() < 1240);
});

A CSS solution:

@media all and (min-width: 1240px) {
    .target {
        display: block;
    }
}
@media all and (max-width: 1239px) {
    .target {
        display: none;
    }
}

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