pbal
pbal

Reputation: 43

Change CSS live based on page width

I am trying to add certain styles to the page based on the current page width. I want this to function live. For example, when viewing on a iPhone and rotating the screen while viewing an already loaded page, the css will change. Also, I would ideally like to use the mobile jquery library. Thanks in advance for the help. Here is what I have so far which doesn't seem to work, I tried using LiveQuery also and that didn't work either

$(function() {
    $(document).live('css_init', function() {
           if (($(window).width()) > 430) {
                $('#main_panels .next').addClass("next-wide");
                $('#main_panels .prev').addClass("prev-wide");

           };
       });
       $(document).trigger('css_init');
});

Upvotes: 1

Views: 2373

Answers (3)

Hersha
Hersha

Reputation: 207

CSS Media Queries should do what you want without the javascript.

Try something like this:

<link rel='stylesheet' media='screen and (orientation:landscape)' href='css/landscape.css' />

You may want to add some hard resolutions contraints but thats easy to do.

http://css-tricks.com/css-media-queries/

Upvotes: 0

Trav McKinney
Trav McKinney

Reputation: 998

could you use the jquery resize event listener?

myFunction() {
    var w = $(window).width();
    if (w > 430){
        // do stuff
    };
}
$(window).resize(function(){
    myFunction();
}

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239440

Stop right now, select all and hit the backspace/delete key on your keyboard.

Now that the horror of that has faded, let me introduce you to Media Queries. This is fully supported on all modern mobile devices (i.e. things with full web browsers, not WAP portals). It is also widely supported already in modern desktop browsers. The only exception is IE<9, and for that, you have Respond.js.

Now, go and bask in the glories of web standards.

Upvotes: 6

Related Questions