10

I'm really tired of syntax like this:

.css('position','absolute').css('z-index',z-index)
.css('border','1px solid #00AFFF').css('margin','-1px 0px 0px -1px')
.css('left',pleft)

I wonder if there's any way to pass all parameters in one function, something like:

.foo('position':'absolute','z-index':z-index,
     'border':'1px solid #00AFFF','margin':'-1px 0px 0px -1px',
     'left':pleft)

Much appreciate any help.

3
  • 1
    Fyi, your code is invalid. z-index is not a valid variable name but z minus index assuming both variables exist; otherwise it's an error. Commented May 25, 2012 at 12:34
  • It's for questions like this that api.jquery.com exists. Also, if you're making that many inline CSS changes, setup a stylesheet and simply use addClass("myclass"); Commented May 25, 2012 at 12:35
  • yeah, it's was just an example... I never had such variables :) Commented May 25, 2012 at 12:35

3 Answers 3

34

Yes, pass an object to .css() (also mentioned in the docs):

.css({
    position: 'absolute',
    left: pleft,
    zIndex: 123
    ...
});

Note that you can use both syntaxes for the keys: zIndex, i.e. the camelcase version that can be used directly in JavaScript and 'z-index' (quotes required as the - would break things otherwise).

For options that are always the same - in your case probably position, border and margin - it might be a good idea to a classic CSS rule set via a class/id selector. Then you'd just have to set the remaining (dynamic) options via .css().

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

Comments

9

Define style in separate class

css

.myCustomClass
{
     position: absolute;
     border: 1px solid #00AFFF
}

And js

.addClass('myCustomClass');

And this is very simple to manage if styles go too complex

3 Comments

Doesn't answer his question and doesn't work if he needs some dynamic values. He still needs .css() for them.
@ThiefMaster anyways, for certain situations this is pretty good solution, worth mentioning :)
that's correct ThiefMaster, I've been using classes for other purposes - but this is not the case
0
$(element).css({'position':'absolute','z-index':zIndex,
     'border':'1px solid #00AFFF','margin':'-1px 0px 0px -1px',
     'left':pleft});

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.