Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript on different screen sizes

I need to let this script run on screen sizes with a width of 794 px or higher. For smaller screen sizes it should not run, because this makes problems with another script.

I have tried different stuff, but I don't really know how to make this happen.

jQuery(document).ready(function ($) {
    $('a[href*=#]:not([href=#])').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
});

Can anyone let me know, how I can adjust this to let this script just run on screen width 794 px or higher?

like image 316
Kish Avatar asked Apr 27 '26 21:04

Kish


1 Answers

You can use window.matchMedia() for media queries in javascript.

for example

var mq = window.matchMedia( "(max-width: 570px)" );
if (mq.matches) {
    // window width is at less than 570px
}
else {
    // window width is greater than 570px
}

For web browser support : Please refer "https://hacks.mozilla.org/2012/06/using-window-matchmedia-to-do-media-queries-in-javascript/"

Update

If you want to run the script only once and not on resizing you can use

if($(window).width()>=794)
{
    //do your stuffs here
}
like image 94
sahil gupta Avatar answered Apr 30 '26 09:04

sahil gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!