28

I've written out a very basic script to add/remove a class on load or when a window is resized.

I was just wondering if there was a better way of doing this or if it is possible to reduce the lines of code.

Basically I want to be able to alter the styles when the site is viewed on a smaller screen. I thought it would be best to add a new class to the html tag when it went under a certain width...

Anyways here's my code.

<script type="text/javascript">
 $(document).ready( function() {
    /* Check width on page load*/
    if ( $(window).width() < 514) {
     $('html').addClass('mobile');
    }
    else {}
 });

 $(window).resize(function() {
    /*If browser resized, check width again */
    if ($(window).width() < 514) {
     $('html').addClass('mobile');
    }
    else {$('html').removeClass('mobile');}
 });

Thanks

Gillian

1
  • 6
    one of the options is using Media Queries Commented Jun 15, 2012 at 8:58

7 Answers 7

57

Well, I know I'm late to the party, but I saw some things like $(document).ready() that weren't really necessary.

Try to cache your selectors if you're calling them over and over again, a la var $window = $(window); This will help with performance. I use a function expression to encapsulate to I stay out of the global scope but still have access to my $window and $html cached jQuery selected elements.

(function($) {
    var $window = $(window),
        $html = $('html');

    $window.resize(function resize(){
        if ($window.width() < 514) {
            return $html.addClass('mobile');
        }

        $html.removeClass('mobile');
    }).trigger('resize');
})(jQuery);

http://jsfiddle.net/userdude/rzdGJ/1

Probably a little cleaner, little easier to follow:

(function($) {
    var $window = $(window),
        $html = $('html');

    function resize() {
        if ($window.width() < 514) {
            return $html.addClass('mobile');
        }

        $html.removeClass('mobile');
    }

    $window
        .resize(resize)
        .trigger('resize');
})(jQuery);

http://jsfiddle.net/userdude/rzdGJ/2

Sign up to request clarification or add additional context in comments.

4 Comments

An example of a GOOD ANSWER :)
probably bet answer here!
that is a really awesome answer -- thank you so much, Jared!
Better late than never! This is a great solution.
16

Use Media classes

@media screen and (max-width: 900px) {
  .class {
    width:800px;

  }
}

@media screen and (max-width: 500px) {
      .class {
        width:450px;

  }
}

3 Comments

I really like this solution, short 'n simple!
I can't explain why, I've just never learned to trust @media queries.
but you must have a strong reason to convince yourself otherwise
16

First of all, DRY (Don't Repeat Yourself) your code by using a function:

function checkWidth(init)
{
    /*If browser resized, check width again */
    if ($(window).width() < 514) {
        $('html').addClass('mobile');
    }
    else {
        if (!init) {
            $('html').removeClass('mobile');
        }
    }
}

$(document).ready(function() {
    checkWidth(true);

    $(window).resize(function() {
        checkWidth(false);
    });
});

2 Comments

You don't really need the $(document).ready() with the window object, and anyhow your checkWidth() function could go inside where you setup the $(window).resize() handler. If you need to call it later out of scope, you can always $(window).resize().
IMHO, I think you do need $(document).ready(), because on Mobile devices, it doesn't work right on the first load. This is just my experience, so take it with a grain of salt!
8
function resize() {
    if ($(window).width() < 514) {
     $('html').addClass('mobile');
    }
    else {$('html').removeClass('mobile');}
}

$(document).ready( function() {
    $(window).resize(resize);
    resize();
});

1 Comment

For some reason, this is the only one that worked really well for me. Thank you!
4

You Can also Use this Method I think its very clear to follow :

$(window).on('resize', function(){
      var win = $(this);
      if (win.width() < 514) { 

      $('html').addClass('mobile');

      }
    else
    {
        $('html').removeClass('mobile');
    }

});

Simple Method

1 Comment

Should be noted that this will only add a class on resize, not on initial page load
2

This issue pestered me for a while, actually. I usually have multiple sizes for transitions. I wrote this an thought I'd share:

$(function() {
  var pageTransitions = [['full',1600],['mobile',800],['tiny',400],['micro',0]]; // number shows minimum size - must be from high to low
  function resize() {
    var target = 0,
        w = $(window).width(),
        h = $('html');
    $.each(pageTransitions, function(index, pageTransition) {
        if( w > pageTransition[1]) {
            target = index;
            return false;
        }
    });
    $.each(pageTransitions, function(index, pageTransition) {
        h.removeClass(pageTransition[0]);
    });
    h.addClass(pageTransitions[target][0]);
  }
  resize();
  jQuery(window).on('resize', function() {
    resize();
  });
});

http://jsfiddle.net/mckinleymedia/ERZ3q/7/

Comments

0

Try this. It works for me

function resize() {
        if ($(window).width() < 514) {}
        else {}
    }

    $(document).ready( function() {
        $(window).resize(resize);
        resize();
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.