How to load a certain script depending on the width of the screen?

0

I have a website which is adapted for mobile but in certain points of interruption or break I need to execute certain Javascript. Example:

I need that when the screen is greater than 992 px a'Click 'event is executed and if it is less than that resolution that nothing is executed or just sends an alert that indicates something.

What I tried was the following:

$(document).ready(function () {
    $(window).resize(function () {
        if ($(Window).width() >= 992) {
            alert('Has cambiado el tamaño de la ventana');
            $(".sidenav-trigger").click(function () {
                alert("Handler for .click() called.");
                $("body").toggleClass("menuclose");
            });
        } else {
            alert("no entraste al if");
        }
    });
});

But for some reason it does not work for me ... who can help me how to make a certain script run depending on the screen of the device?

    
asked by vcasas 14.08.2018 в 18:32
source

2 answers

1

What I would do would be to encapsulate your code in a separate function which would be executed immediately load the document, this in order not to depend solely on the event resize() since when opening your site on a mobile this event obviously it will not be executed in the first instance because the user is not changing the screen size at any time.

$(document).ready(function () {
    $(window).resize(function () {
         cambio();
    });
    
    cambio();
    
    function cambio(){
      if ($(window).width() >= 992) {
            alert('Has cambiado el tamaño de la ventana');
            $(".sidenav-trigger").click(function () {
                alert("Handler for .click() called.");
                $("body").toggleClass("menuclose");
            });
        } else {
            alert("no entraste al if");
            $(".sidenav-trigger").off();
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="sidenav-trigger">Botón</button>
    
answered by 14.08.2018 / 18:49
source
0

The problem is that you only declare the handler, but you have to call it explicitly with trigger like this:

$(document).ready(function () {
    $(window).resize(function () {
        if ($(window).width() >= 992) {
            alert('Has cambiado el tamaño de la ventana');
            $(".sidenav-trigger").click(function () {
                alert("Handler for .click() called.");
                $("body").toggleClass("menuclose");
            });
            $(".sidenav-trigger").trigger('click');
        } else {
            alert("no entraste al if");
        }
    });
});
    
answered by 14.08.2018 в 18:43