How to set overflow-x with jQuery? Or: How to set css-properties with a '-' (dash)?

37,228

Solution 1

You could use either camel-case:

$('.mySelector').css({
    color: 'Red',
    overflow: 'auto',
    overflowX: 'scroll'
});

Or quoted keys:

$('.mySelector').css({
    color: 'Red',
    overflow: 'auto',
    'overflow-x': 'scroll'
});

I would recommend quoted keys, I find it easier to tell 'at a glance' what a rule is compared to camel-casing.

Solution 2

You can quote it (with single or double quotes) or use the camel case variant (which the DOM adopted with its style object, because - are not legal in identifiers).

$('.mySelector').css({
    'color': 'Red',
    'overflow': 'auto',
    'overflow-x': 'scroll'
});
Share:
37,228
Kees C. Bakker
Author by

Kees C. Bakker

Senior Software Developer and Team Manager for Capital ID - a leading international supplier specialized in automating and managing marketing processes (MRM, MOM), using its software platform ID Manager. Specialties: C# / ASP.Net Html / CSS jQuery / JavaScript (T)SQL Visit my blog: KeesTalksTech.com Follow me: twitter.com/KeesTalksTech LinkedIn: linkedin.com/in/keescbakker

Updated on February 26, 2020

Comments

  • Kees C. Bakker
    Kees C. Bakker about 4 years

    I would like to set the overflow-x css property with jQuery, but it doesn't work:

    $('.mySelector').css({
        color: 'Red',
        overflow: 'auto',
        overflow-x: 'scroll'
    });
    

    How would I set properties that have a '-' (dash) in them?

  • Kees C. Bakker
    Kees C. Bakker almost 13 years
    Could I set all '-' properties like this?
  • Kees C. Bakker
    Kees C. Bakker almost 13 years
    Could I set all '-' properties like this?
  • Kees C. Bakker
    Kees C. Bakker almost 13 years
    Can I combine non-quoted and quoted, like { color: 'Red', 'overflow-x': 'scroll' }?
  • Kees C. Bakker
    Kees C. Bakker almost 13 years
    Why did you edit your answer, your original answer with overflowX worked very good :-)
  • Michael Robinson
    Michael Robinson almost 13 years
    @Kess, sorry, I'm on a very slow connection and was in the middle of researching my answer in order to make sure it was as accurate as possible