EzDevInfo.com

matchMedia.js

matchMedia polyfill for testing media queries in JS

webkit memory leak on page refresh?

We came across this issue while investigating low memory crashes on iOS Mobile Safari.

Most noticeably on a large HTML5 application, like a HTML5 game, we've found a memory leak on the browser where memory will keep adding up on every refresh.

In our case, the app runs with about 300MB of real memory usage and it added up around 100MB on every refresh.

Most noticeably on iPad mini and iPad4, it would crash Mobile Safari immediately after a couple of refreshes.


Source: (StackOverflow)

Adding listener to matchMedia.js polyfill issue

I am using https://github.com/paulirish/matchMedia.js/ along with the listener extension, however, I do not know how to write a listener for the match media query below. Any assistance would be much obliged.

JS:

if (matchMedia("(min-width: 52em)").matches) {
  $("details").attr("open", "open");
}

Source: (StackOverflow)

Advertisements

Switch between Superfish and FlexNav depending on window width

I am trying to use 2 jQuery navigation scripts on one page (Superfish for desktops and FlexNav for mobile). I am currently using matchMedia along with the polyfill by Paul Irish to respond to CSS3 media query state changes within JavaScript.

The current code is only accomplishing 50% of the overall goal. If you access the web page initially with a window size equal to or greater than 999px wide then you get Superfish and if you initially access the web page with a window size less than 999px then you get FlexNav. The problem occurs when you resize the window above or below 999px as both scripts become active.

// media query event handler
if (matchMedia) {
    var mq = window.matchMedia("(min-width: 999px)");
    mq.addListener(WidthChange);
    WidthChange(mq);
}
// media query change
function WidthChange(mq) {
    if (mq.matches) {
        $("ul.sf-menu").superfish({
            delay: 350,
            speed: 400,
        });
    } else {
        $("ul.flexnav").flexNav({
            'animationSpeed': '250',
            'transitionOpacity': true,
            'buttonSelector': '.menu-button',
            'hoverIntent': false
        });
    }
}

As much as I would like to get this working with matchMedia, I am open to all suggestions.

Update: Thanks to Stephan's suggestion I now have the following code:

jQuery(document).ready(function () {
    // add destroy function for FlexNav
    flexNavDestroy = function () {
        $('.touch-button').off('touchstart click').remove();
        $('.item-with-ul *').off('focus');
    }
    // media query event handler
    if (matchMedia) {
        var mq = window.matchMedia("(min-width: 999px)");
        mq.addListener(WidthChange);
        WidthChange(mq);
    }
    // media query change

    function WidthChange(mq) {
        if (mq.matches) {
            if (typeof (flexNav) != "undefined") {
                flexNavDestroy();
            }
            superfish = $("ul.sf-menu").superfish({
                delay: 350,
                speed: 400,
            });
        } else {
            if (typeof (superfish) != "undefined") {
                superfish.superfish('destroy');
            }
            flexNav = $("ul.flexnav").flexNav({
                'animationSpeed': '250',
                'transitionOpacity': true,
                'buttonSelector': '.menu-button',
                'hoverIntent': false
            });
        }
    }
});

Remaining Issue: The destroy function for FlexNav is only partially destroying it.


Source: (StackOverflow)

Angularjs Matchmedia on page routing

How can I perform a matchmedia for page routing below. That is I would like load a different templateURL for home if it is a tablet?

app.config(['$routeProvider',function($routeProvider) {
        //configure the routes
        $routeProvider

        .when('/',{
        // route for the home page
            templateUrl:'partials/login/login.html',
            controller:'loginCtrl'      
        })

        .when('/home',{
        // route for the home page

            templateUrl:'partials/home/home.html',
            controller:'mainCtrl'       
        })

        .otherwise({
            //when all else fails
            templateUrl:'partials/login/login.html',
            controller:'loginCtrl'
        });


}]);

Source: (StackOverflow)

window.matchMedia not changing even if media queries are present

There's a CSS file with these rules:

@media screen and (orientation:portrait) {
  .foo {}
}
@media screen and (orientation:landscape) {
  .foo {}
}

And then I've got this script, running on orientationchange:

function checkOr(){
    if (window.matchMedia("(orientation:portrait)").matches) {
      console.log('portrait ' + window.orientation);
    } else {
      console.log('landscape '+ window.orientation);
    }
}

But matchMedia always returns initial state of the page, when window.orientation returns correct value:

portrait -90
portrait 0
portrait -90

Tested on iPhone 5 and iPad 4 with latest iOS updates.

What am I doing wrong? Webkit bugtracker says that there must be rules for each media query, but that's not my case.


Source: (StackOverflow)

Remove/add css classes on breakpoint with matchmedia.js

I have following code which works fine when the screen size is 770px and below (as determined by breakpoints):

    var handleMatchMedia = function (mediaQuery) {
      if (mediaQuery.matches) {

         $j(".view-all a").removeClass("button");
         $j(".view-all").removeClass("view-all");

    } else {

        $j(".view-all a").addClass("button");
        $j(".view-all").addClass("view-all");
    }
},

mql = window.matchMedia('all and (max-width: 770px)');

handleMatchMedia(mql); 
mql.addListener(handleMatchMedia); 

The problem is when the window is resized to 770px and up I lose my classes.

How to achive to change class on window resize?


Source: (StackOverflow)

Remove dynamically registered events at a later point

So I have this code that registers an event to an array of breakpoints:

var breaks = ["(min-width: 800px)","(min-width: 300px)"];

var breakChange = function(mq) {
  console.log(mq);
}

for ( i = 0; i < breaks.length; i++ ) {  
  var mq = window.matchMedia(bG.breaks[i]);
  mq.addListener(breakChange);
}

It works great, but I want to be able to remove the listeners from these breaks at a later point. Does anyone know what would be the best way to go about removing event listeners registered dynamically at a later point?


Source: (StackOverflow)

should matchMedia orientation become Landscape when I enter data into a form field?

On my S3 both Chrome and Firefox fire a matchMedia event saying I'm in landscape mode when I'm in portrait mode and touch a data entry field to enter data. On my iPad, this does not happen. It is certainly undesirable to announce orientation has changed when it hasn't - is this spurious landscape orientation event per spec? home.comcast.net/~tommoran4/bug.htm demonstrates the problem.


Source: (StackOverflow)

Include jQuery script at footer only on mobile and resize friendly

I'm trying to incorporate a jQuery plugin by Codrops - that make turns the menu into a bar on the left and bottom. I'd like to use the same menu as a normally top bar on desktop screens, just changing the styles of the id and classes that come with the demo. I was wondering whats the best Javascript solution to include the plugin's scripts on max-width of 768 and then remove them on anything larger. I'd like it to self check and update on browser resize too. Here's what I have so far...

 <script>
  (function() {
if( window.innerWidth > 600 ) {
   $.getSscript("assets/js/modernizr.custom.js");
   $.getSscript("assets/js/classie.js");
   $.getSscript("assets/js/borderMenu.js");
}
 })();
 </script>

Source: (StackOverflow)

Polyfill for enquire.js in wordpress

I'm trying to use Enquire.js in my Wordpress install. I'm trying just to push the left column under the central column for small screens.

I got it to work in most browser my the laptop, but it does not work on older Androids browser (2.2), saying it needs a polyfill. I tried to get this polyfill to work, but still not getting the functionality on Android, I still get the warning about matchmedia polyfill in android console.

Please help me pinpoint what is possible problem. Basically, I load couple of scripts in function.php:

function rr_scripts() {
  wp_enqueue_script( 'polyfill', get_stylesheet_directory_uri() . '/js/polyfill.js', array( 'Modernizr' ), '1.0.0', true );
  wp_enqueue_script( 'enquire', get_stylesheet_directory_uri() . '/js/enquire.js', array( 'jquery' ), '1.0.0', true );
  wp_enqueue_script( 'reorder', get_stylesheet_directory_uri() . '/js/reorder.js', array( 'enquire' ), '1.0.0', true ); 
} 
add_action( 'wp_enqueue_scripts', 'rr_scripts' );

Then my Child template has js folder with couple of files, polyfill.js, that is supposed to polyfill the mediamatch (media.match.js is in the same folder):

Modernizr.load([
{
    test: window.matchMedia,
    nope: "media.match.js"
} ]);

reorder.js (below), that actually uses the enquire.js that is in the same folder as well:

jQuery(document).ready(function() {
   enquire.register("screen and (max-width: 599px)", {
       match: function() { jQuery('#leftside').insertAfter('#primary'); },
       unmatch: function() { jQuery('#leftside').insertBefore('#primary'); }
   }); 
});

Source: (StackOverflow)

Adaptive ("image ID + text string") JavaScript for Responsive Images

I've been using the following code for my responsive image replacements:

//HTML:

<img id="testimage" onLoad="minWidth32('test_image')" src="testimage_small.jpg">


//JavaScript:

var screencheck = window.matchMedia("(min-width: 32em)");
function minWidth32(imageName) {
   if (screencheck.matches) {
      currentImage = document.images[imageName];
      currentImage.src = imageName + "_large.jpg";
   }
}

(edit)New streamlined version of JavaScript:

var screencheck = window.matchMedia("(min-width: 32em)");
function minWidth32(imageID) {
   if (screencheck.matches) {
      document.getElementById(imageID).src = imageID + "_large.jpg";
   }
}

I really love the "image ID + text string" method for image changes. It allows a single script (per media query) to run as many images as necessary. Many responsive image scripts/plug-ins/libraries involve so. much. mark-up.

But this particular script only sort-of works:

1.) Originally designed for "onMouseOver" rollover effects, this script requires an event listener. This isn't ideal for a responsive images script since browsers are resized and mobile devices change orientation long after an "onLoad" event is over.

2.) This script can only change a non-empty src attribute (from "test_image_small.jpg" to "test_image_large.jpg" in the above example). This means both images are still loaded, wasting bandwidth and making the layout jump around obnoxiously. I'd prefer to fill an empty src attribute.

So basically what I need - and haven't been able to figure out - is this:

//if (screencheck.matches &&
 //item is an image tag &&
 //item has empty src attribute &&
 //item has non-empty ID attribute) {
   //set item src attribute = item ID attribute + a text string
//}

Source: (StackOverflow)

Bxslider reloadSlider not triggering updating slideWidth when called with Enquirejs

I've implemented bxslider on a project and to make it work on mobile and tablets I integrated it with enquirejs. When emulating it in Chrome it works fine when you reload the page but as soon as you change the orientation from portrait to landscape the slider does not update the slide width, and vice versa.

Here is the jquery code:

    adob_slider = $('.mobile-circular-timeline').bxSlider({
    });

      var adob_setting_max = {
        slideWidth: ($(window).width())/2,
        minSlides: 1,
        maxSlides: 1,
        moveSlides: 1,
        pager: false,
        easing: 'linear',
        controls: false,
        infiniteLoop: false,
        hideControlOnEnd: true,
        slideMargin: 0
      }
      var adob_setting_min = {
        slideWidth: ($(window).width())/6,
        minSlides: 6,
        maxSlides: 6,
        moveSlides: 6,
        pager: false,
        easing: 'linear',
        controls: false,
        infiniteLoop: false,
        hideControlOnEnd: true,
        slideMargin: 0
      }

var max_query = "(max-width:480px)",
    max_handle = {
  setup : function() {
  },
  match : function() {
    adob_slider.reloadSlider(adob_setting_max);
  },      
  unmatch : function() {
    adob_slider.reloadSlider(adob_setting_min);
  },
  destroy : function() {
  }
}
enquire.register(max_query, max_handle);

The complete code is under document.ready

Ideally it should appear like this on landscape mode: http://awesomescreenshot.com/0783eeb331

but instead on orientation change it is appearing like this: http://awesomescreenshot.com/0163eeb6fb

Any help would be appreciated. Cheers!!

UPDATE: I tried with mediaCheck plugin and also with directly with matchMedia and the same issue is occurring. So it seems it a problem with bxslider only.


Source: (StackOverflow)

Stop jQuery function using screen width

I am struggling with the following: I want to change the behaviour of my header, depending on the Screen width. It works just fine when going from small to big resolution. But the other way round the "ganzOben" and "inMitte" functions don't stop. Any Ideas?

$(document).load($(window).bind("resize", checkHeader));
$(document).ready(checkHeader ());
$(window).scroll(checkHeader ());

function checkHeader(){
    if (window.matchMedia('(min-width: 725px)').matches) {
            $(window).scroll(function ganzOben (){
                if($(document).scrollTop() <= 0) {
        /* CSS for Header Desktop Res TOP */
                }
            });
        var lastScrollTop = 0;
        $(window).scroll(function inMitte (event){
            var st = $(this).scrollTop();
            if (st > lastScrollTop){
        /* CSS for Header invisble by Downscolling */
            } else {
        /* CSS for Header visible by Upscolling */
            }
            lastScrollTop = st;
        });
    } else {
        $(window).scroll(function inMitte (event) {return false});
        $(window).scroll(function ganzOben () {return false});
        /* CSS for Header in mobile View */
    };
};  

`


Source: (StackOverflow)

Angular: Orientation change not working properly

I'm working on an angular-app and am trying to implement orientation change with matchmedia. When I first load my page I run a line of code in my controller to check wheter if i'm in landscape or not:

$scope.landscape = matchmedia.isLandscape();

This works fine. But then when I want to detect a change of orientation I use this code:

angular.element($window).bind('orientationchange', function () {
    $route.reload();
});

So when the orientation changes the page gets reloaded and it will again detect the orientation. But now it gives back the opposite. So it says landscape == false when it should be true. Does anybody know why this is? Or am I using a wrong technique to deal with the orientation change? Thanks in advance!


Source: (StackOverflow)

matchMedia calls functions twice

I am trying to use a function on mobile devices (less than 700px in this example) and another function on large devices. I use matchMedia in the following way:

var mql = window.matchMedia("(min-width: 700px)");
mql.addListener(handleResize);
handleResize(mql);
function handleResize(mql) {
    if (mql.matches) {      
    $(".button").on("click", function(){
        $(".hidden").slideToggle();
    })                 
  } else {  
    $(".button").on("click", function(){
        $(".hidden").fadeToggle();
    })   
  }
}

At first, the code behaves as expected, the problem occurs when I resize the window. For instance, if the window first loads under 700px and then is resized to more than 700px, the button fires fade first, then slide and vice versa. What I want to achieve off course is calling only slide on large sreens and only fade on small screens. Any help is greatly appreciated.

Cheers!


Source: (StackOverflow)