How to Use Conditional Javascript

Updated on April 08, 2016
I created this post to continue the previous post about the mobile user. In the previous post I said that in order to blog more responsive mobile friendly it is necessary to remove some elements and javascript on mobile display. So for mobile should we just mem-kan-focus on the content or postings (including comments in it). While for sidebar and javascript apart Google Analytics tracking script we hide or lose.
AuthorAdhy Suriady
Now we will discuss this time is conditional javascript from Mr. + Patrick Sexton to eliminate javascript on mobile display. Actually, the posting is clear enough, but because there are a few English-speaking bloggers are difficult to translate. So here I will explain its use in a simple to be easy to understand. Conditional javascript is like the code below:
<script type='text/javascript'>
//<![CDATA[
var mql = window.matchMedia('screen and (min-width: 800px)');if (mql.matches){
Javascript di sini
}
//]]>
</script>
Or it could be like this:
<script type='text/javascript'>
//<![CDATA[
if (window.matchMedia("(min-width:800px)").matches){
Javascript di sini
}
//]]>
</script>
If defined, above javascript code as follows: If the window (screen) of at least 800px, then use this javascript code ( Javascript here ) . or use javascript on the screen width of 800px to the top .
That way when the screen has a width of less than 800px then javascript is not used. So please save javascript that do not want to appear in mobile (below 800px width) on Javascript here . 

For example javascript, please see below.
<script type='text/javascript'>
//<![CDATA[
var mql = window.matchMedia('screen and (min-width: 800px)');if (mql.matches){
var button=document.querySelector("#close-pengumuman");button.addEventListener("click",function(){var t=document.querySelector(button.getAttribute("data-target"));t.style.display="none"==t.style.display?"block":"none"});
}
(function(e,t,n,r,i,s,o){e["GoogleAnalyticsObject"]=i;e[i]=e[i]||function(){(e[i].q=e[i].q||[]).push(arguments)},e[i].l=1*new Date;s=t.createElement(n),o=t.getElementsByTagName(n)[0];s.async=1;s.src=r;o.parentNode.insertBefore(s,o)})(window,document,"script","//www.google-analytics.com/analytics.js","ga");ga("create","UA-XXXXXX-1","auto");ga("send","pageview");
//]]>
</script>
If you read, then the javascript above as follows: 
Effect on the close button #close-announcement will work on screen with a width of at least 800px (on screen below 800px javascript effects does not work) , while for the code tracking Google Analytics unaffected conditional javascript so work in all the width of the device. Or if any javascript just want displayed on mobile only (width 800px down), then just change the code min-width with max-width .
Share this: pinterest