save meta width in variable session Javascript

1

I'm working on a page which I want when the user presses 'full version', force the width of the meta to make it look like the real web, the script does something like this:

((function ( $ ) {

    var mobile = true;

    var targetWidth = 1100;

    $('.mobile-to-desktop').click(function(e) {
        e.preventDefault();
        $('meta[name="viewport"]').attr('content', 'width=' + targetWidth);
        $('.watch-mobile').addClass('active');
        window.sessionStorage.setItem("mobile", "false");
    });

    $(function() {
        if (window.sessionStorage.getItem("mobile") === false) {
            $('meta[name="viewport"]').attr('content', 'width=' + targetWidth);
            $('.watch-mobile').addClass('active');
        }
    });

})(jQuery));

This works perfectly, the problem is that when I change php, the width changes again, and I wanted to see if it can be saved in some way.

I tried the sessionStorage and localStorage, but it does not work for me, it's just because I'm using something wrong.

    
asked by Imanol 07.04.2016 в 09:34
source

1 answer

1

The sessionStorage.getItem method returns a DOMString (it's basically the same as String in javascript) so the comparison window.sessionStorage.getItem("mobile") === false will always return false since you are using the strict comparison === .

You can use the relaxed comparison operator == but this is usually not recommended as it is a source of very hard to find bugs. Instead you should compare with the exact value you put "false" as a string.

(function($) {

  $(function() {
     var mobile = true;

     var targetWidth = 1100;

     function setDesktopMode() {
       $('meta[name="viewport"]').attr('content', 'width=' + targetWidth);
       $('.watch-mobile').addClass('active');
     }

     $('.mobile-to-desktop').click(function(e) {
       e.preventDefault();
       setDesktopMode();
       window.sessionStorage.setItem("mobile", "false");
     });

     if (window.sessionStorage.getItem("mobile") === "false") {
       setDesktopMode();
       mobile = false;
     }

  });

}(jQuery));

The first time it works because you are changing it with jquery but the second time the value is not compared correctly and it does not work.

In my example, I wrapped all the code in the DOMReady jquery event, since you should not set event handlers or search items until the DOM has not been fully loaded.

I also deleted the redundant parentheses in the IIFE

((function() {
   //código
})());

functiona same as

(function() {
   // código
} ());

// o

(function() {
   //código
})();

Except you have a pair of redundant parentheses that can make it harder to read the code.

    
answered by 07.04.2016 / 14:15
source