1

I am using jquery to dynamically place content based on screen resolution. If the resolution is below 800px in width I want to adjust the elements as necessary but when the window is resized above 800px in width I want the css styles that are already defined in by external css file to be applied to the elements again. I can go through and change everything back again manually but it seems redundant. Is there an object oriented css trick or jquery function that I could use to do this?

Example

    $(window).resize(function()
    {
        if(this.resizeTO) 
            clearTimeout(this.resizeTO);
        this.resizeTO = setTimeout(function() 
        {
            if(window.innerWidth < 800)
            {
                $("#usernameDisplay").css({top: "50px", right:"50%", "margin-right": "-" + $("#usernameDisplay").width()/2 + "px", "padding-top":"0px"});   
                $("#headerBack").css("height", "95px");
                $("#userMenuContainer").css({top: "95px", right:"50%", "margin-right": "-" + $("#userMenuContainer").width()/2 + "px"});
            }
            else
            {
                $("#usernameDisplay").css({top: "0px", right:"0", "margin-right": "0", "padding-top":"10px"});  
                $("#headerBack").css("height", "55px");
                $("#userMenuContainer").css({top: "110px", right:"0", "margin-right": "0"});
            }
        }, 200);
    });
6
  • 1
    So use .addClass() and get rid of style attribute
    – Mr. Alien
    Jan 14, 2014 at 8:42
  • @Mr.Alien: That works well for applying static either/or values, less so for values you are calculating on-the-fly ($("#usernameDisplay").width()/2 + "px" for instance). Jan 14, 2014 at 8:48
  • I don't see how this is a duplicate. I'm asking to reapply previously defined css. Not replace it. Jan 14, 2014 at 8:48
  • @CraigPatrickLafferty: You're asking how to remove inline styles (so the CSS rules take over). That question asks how to remove inline styles (and has ready answers). Or are we misunderstanding? Jan 14, 2014 at 8:50
  • @T.J.Crowder Oh I see, learning bee here :)
    – Mr. Alien
    Jan 14, 2014 at 8:51

1 Answer 1

3

If your CSS rules apply a style, say:

.foo {
    left: 20px;
}

And you have an element that applies to:

<div class="foo">...</div>

If you then set the style value on the element itself, it overrides the CSS rule:

$(".foo").css("left", "30px"); // Or whatever

Note that it overrides it, it doesn't overwrite it.

If you then remove that style value from the element itself:

$(".foo").css("left", "");

...the CSS rule applies again and (in this case) the left property goes back to being 20px.

If you want to remove all inline styles you've applied to the element, you can do that by clearing the style attribute:

$("#usernameDisplay").attr("style", "");

Not the answer you're looking for? Browse other questions tagged or ask your own question.