-2

Today I have a question for the best syntax on Js :

Here is the usual version

function resize() {
    if ($(window).width() < 960) {
        $('. slect span').click(function () {
            $('.home-footer').toggleClass('open-in-mob');
        });
    } else {
        $('.home-footer').removeClass('open-in-mob');
        $('. slect span').click(function () {
            $('.home-footer').toggleClass('open-in-mob');
        });
    }
}
$(document).ready(function () {
    $(window).resize(resize);
    resize();
});

And here here is an other version that works, but, I would have your opinion:

if (matchMedia('only screen and (max-width:959px)').matches) {
    $(".slect span").click(function(event) {
        $(this).parents(".home-footer").addClass("open-in-mob");
    });
}

If you think that an other syntax is better, please share :) thanks

Johan
  • 19
  • 4
  • Whats `matchMedia` ?! – Jonas Wilms May 24 '18 at 13:51
  • 1
    @JonasW.: https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia – T.J. Crowder May 24 '18 at 13:52
  • Something I found here : https://github.com/paulirish/matchMedia.js/ https://www.alsacreations.com/article/lire/1500-matchmedia-javascript-media-queries.html – Johan May 24 '18 at 13:52
  • 1
    It's entirely up to you. If you only need to support browsers [that support `matchMedia`](https://caniuse.com/#feat=matchmedia) and you prefer to use it, use it. If you don't, don't. But note that **both** your code snippets have the problem that as the window width changes, they register and re-register click handlers, which is a classic error. Also note that your selectors in the first block are invalid. – T.J. Crowder May 24 '18 at 13:54
  • @T.J.Crowder thanks Yes right, selector was just to illustrate my question. Ok, any other way to do same thing but little better ? – Johan May 24 '18 at 13:58

1 Answers1

0

This may be easier/simplified by using CSS media queries. Adding JS into the mix to control page layouts should be used as a last resort. The more times you have a DOM reflow the slower your page speed.

Example with CSS:

@media (max-width: 960px) {
    // Your code here
}

https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

  • Hello @DonCarlos, Not good because, I'm adding a function on clic. In .css, rule will be applied directly. OR, I should add my class rules only on responsive view.. hmm, testing.. – Johan May 24 '18 at 14:17