2

I have this JS function which centers everything on the page. This is called at the start of the page and automaticly centers when the window is resized.

I need a way to make the function not center anything when the web page is loaded on a mobile device.

 /**
     * This method centers a DOM element vertically and horizontally
     * on the page.
     * 
     * @param {object} elementHandle The object that is going to be 
     * centered.
     */
    centerElementOnPage: function(elementHandle) {
        // Center main frame vertical middle
        $(window).resize(function() {
            var elementLeft = ($(window).width() - elementHandle.outerWidth()) / 2;
            var elementTop = ($(window).height() - elementHandle.outerHeight()) / 2;
            elementTop = (elementTop > 0 ) ? elementTop : 20;

            elementHandle.css({
                position: 'absolute',
                left: elementLeft,
                top: elementTop
            }); 
        });
        $(window).resize();
    },

Edit :

Thanks for the css . The JS was messing up some other aspects of the page , so the css helps.

Jess
  • 133
  • 3
  • 12
  • 3
    Just detect if on mobile and don't run the code if it is. See http://stackoverflow.com/questions/11381673/detecting-a-mobile-browser – GillesC Jun 09 '15 at 10:09
  • 2
    You'd be better off [detecting screen resolution](http://stackoverflow.com/questions/2242086/how-to-detect-the-screen-resolution-with-javascript) rather than a mobile device – Liam Jun 09 '15 at 10:11
  • Just on Mobile device or on both Mobile & iPads as well? – Parkash Kumar Jun 09 '15 at 10:17
  • just mobiles , anything with width lower than 500px – Jess Jun 09 '15 at 10:17
  • A width lower than 500px frequently describes the window size of the browser on my laptop. – Quentin Jun 09 '15 at 10:27

1 Answers1

1

Have you considered using CSS Media Queries? You can center/not center things depending on screen size. AFAIK there is no reliable method to determine is it a "mobile device" even with JS, except guessing by screen size. Probing user agent is not reliable either.

A very crude and simple example:

/* Center all the things! */
@media (min-width: 500px) {
  div {
    margin: 0 auto;
    text-aling: left;
  }
}

/* No fun allowed :( */
@media (max-width: 499px) {
  div {
    margin: 0;
    text-aling: left;
  }
}

One important note! This unsupported in older browsers - mainly IE8. http://caniuse.com/#feat=css-mediaqueries

Anton Melnikov
  • 1,048
  • 7
  • 21