4

First of all, I'm not a javascript expert. I'm going crazy on trying to figure out how to make a conditional execution of a certain javascript. I'm using JQuery to absolutely center my block in a browser page, but only if the screen size is bigger than 480px (In other meaning, I don't want this script to run on smartphones). I'm using CSS media query to indicate my request. The thing is, this script works fine on all smartphones, Safari 5+, IE10, Firefox 13. BUT IT DOESN'T WORK ON IE6-9 and Opera 12 (As far as I understand, they don't support transitions). CAN ANYONE PLEASE HELP ME FIGURE OUT WHAT I AM DOING WRONG? And if there's a better way of doing this? (I tried @media query in CSS but The script keeps on running no matter what)... I would really appreciate the help.

    <script>
    if (matchMedia('only screen and (max-device-width:800px) and ' + '(orientation: portrait)').matches) {
        // smartphone/iphone... maybe run some small-screen related dom scripting?
        event.preventDefault(); 
    } else{


        //Absolute Content Center
        function CenterItem(theItem){
            var winWidth=$(window).width();
            var winHeight=$(window).height();
            var windowCenter=winWidth/2;
            var itemCenter=$(theItem).width()/2;
            var theCenter=windowCenter-itemCenter;
            var windowMiddle=winHeight/2;
            var itemMiddle=$(theItem).height()/2;
            var theMiddle=windowMiddle-itemMiddle;
            if(winWidth>$(theItem).width()){ //horizontal
                $(theItem).css('left',theCenter);
            } else {
                $(theItem).css('left','0');
            }
            if(winHeight>$(theItem).height()){ //vertical
                $(theItem).css('top',theMiddle);
            } else {
                $(theItem).css('top','0');
            }
        }
        $(document).ready(function() {
            CenterItem('.content');
        });
        $(window).resize(function() {
            CenterItem('.content');
        });
    } //end of "else" (normal execution)

</script>
Leo
  • 43
  • 5

4 Answers4

2

You can try this :-

<script>
    var screenWidth = screen.width;

    if (screenWidth > 480 ) {

    //Absolute Content Center
    function CenterItem(theItem){
        var winWidth=$(window).width();
        var winHeight=$(window).height();
        var windowCenter=winWidth/2;
        var itemCenter=$(theItem).width()/2;
        var theCenter=windowCenter-itemCenter;
        var windowMiddle=winHeight/2;
        var itemMiddle=$(theItem).height()/2;
        var theMiddle=windowMiddle-itemMiddle;
        if(winWidth>$(theItem).width()){ //horizontal
            $(theItem).css('left',theCenter);
        } else {
            $(theItem).css('left','0');
        }
        if(winHeight>$(theItem).height()){ //vertical
            $(theItem).css('top',theMiddle);
        } else {
            $(theItem).css('top','0');
        }
    }
    $(document).ready(function() {
        CenterItem('.content');
    });
    $(window).resize(function() {
        CenterItem('.content');
    });
}

</script>
Subhajit
  • 1,929
  • 3
  • 19
  • 21
  • MANY THANKS.... Your solution actually works, mate :) It worked on both IE8 and Opera 12, as well as iOS 5 and WP7... Thanks, mate :))) – Leo Jun 20 '12 at 09:36
2

To get exact Height and Width in all browser is quite big deal because of IE, But no worries is the solution for all Browser including IE 6 to latest.

Here are those 2 function:

     if (matchMedia('only screen and (max-device-width:800px) and ' + '(orientation: portrait)').matches) {
        // smartphone/iphone... maybe run some small-screen related dom scripting?
        event.preventDefault(); 
    } else{


        //Absolute Content Center

        $(document).ready(function() {
            CenterItem('.content');
        });
        $(window).resize(function() {
            CenterItem('.content');
        });
    } //end of "else" (normal execution)



function CenterItem(theItem){
                  var winWidth=getWindowWidth();
                  var winHeight=getWindowHeight();
                  var windowCenter=winWidth/2;
                  var itemCenter=$(theItem).width()/2;
                  var theCenter=windowCenter-itemCenter;
                  var windowMiddle=winHeight/2;
                  var itemMiddle=$(theItem).height()/2;
                  var theMiddle=windowMiddle-itemMiddle;
                  if(winWidth>$(theItem).width()){ //horizontal
                      $(theItem).css('left',theCenter);
                  } else {
                      $(theItem).css('left','0');
                  }
                  if(winHeight>$(theItem).height()){ //vertical
                      $(theItem).css('top',theMiddle);
                  } else {
                      $(theItem).css('top','0');
                  }
              }

function getWindowHeight() {
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {

    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {

    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {

    myHeight = document.body.clientHeight;
  }
  return myHeight;
}
function getWindowWidth() {
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {

    myWidth = window.innerWidth;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {

    myWidth = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {

    myWidth = document.body.clientWidth;
  }
  return myWidth;
}

This will help you to get exact height in any Browser, in that way you can apply your logic. Hope this help!!!

Ishan Dhingra
  • 2,442
  • 5
  • 31
  • 42
  • Thanks, Ishan, for your help... As I said, I'm no javascript expert. I'm only learning. So where do I put the code of yours in my script? – Leo Jun 20 '12 at 09:29
2

Simplest thing is not to attach the event handler if the media query does not match.

$.fn.extend({
    centerItem: function () {
        return this.each(function () {
            var $this   = $(this),
                hCenter = ( $(window).width() - $this.width() ) / 2,
                vCenter = ( $(window).height() - $this.height() ) / 2;

            $this.css({
                left: hCenter > 0 ? hCenter : 0,
                top:  vCenter > 0 ? vCenter : 0
            });
        });
    }
});

$(function() {
    var bigScreen = 'only screen and (max-device-width:800px) and (orientation: portrait)';

    if ( matchMedia(bigScreen).matches ) {
        $(window).resize(function() {
            $('.content').centerItem();
        });
    }
});

Notes

  • $() replaces $(document).ready(). See http://api.jquery.com/ready/
  • By convention, only object constructors start with a capital letter, so your CenterItem() function should actually be called centerItem().
  • I've turned your function into a jQuery plugin. You can of course continue using your own implementation if you find that confusing.
  • The .css() function can take an object argument so you can set multiple CSS properties in one step.
  • I've used the ternary operator (expression ? ifTrue : ifFalse) to replace the if.
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Thanks, Tomalak, but it seems there's an error with the code, as my console tells that an expected token ')' is missing... – Leo Jun 20 '12 at 10:01
1

You can do

window.innerHeight
window.innerWidth

to get the dimensions of the viewport. Now you could do:

var width = window.innerWidth
if (width > 480){
      /* do desktop stuff*/
}

As alternative, you could go for the UserAgentString and/or Operating with:

window.navigator

(more reliable Detect-script)

However, either attempt might fail in some cirumstances.

edit: would be nice if you posted your match-media function.

edit2: use the script for correct viewport detection: https://stackoverflow.com/a/2035211/1047823

and then alter your code:

if ( getViewport()[0] < 480 ) {
        // smartphone/iphone... maybe run some small-screen related dom scripting?
        event.preventDefault(); 
    } else{
        // your desktop code
}
Community
  • 1
  • 1
Christoph
  • 50,121
  • 21
  • 99
  • 128
  • Thanks, Christoph, for your help... I tried adding those vars but it didn't work... Any ideas? – Leo Jun 20 '12 at 09:30
  • This is my whichmobile(); function: `function whichmobile() { var useragentstring=navigator.userAgent.toLowerCase(); alert(useragentstring); var mobilelist=new Array(("iphone os 6", "iphone os 5","ipad; cpu os 5","iphone","ipad","android 2","android", "windows phone os 7.5", "Windows nt 6.1", "blackberry","palmos", "nokia; lumia 800")); for (var device in mobilelist) { if (useragentstring.indexOf(mobilelist[device])>=0) { return mobilelist[device]; break; } } } }` – Leo Jun 20 '12 at 09:32