Return to Video

Changing CSS styles (Video Version)

  • 0:00 - 0:04
    Okay, now you know how to change
    the contents of an element
  • 0:04 - 0:06
    and the values of its attributes.
  • 0:06 - 0:11
    What else is left? Well, what if
    we wanted to change its style?
  • 0:11 - 0:16
    Normally, we would do that in CSS,
    but there are some times when we
  • 0:16 - 0:20
    want to do that in JavaScript, like when
    we want to animate styles over time or
  • 0:20 - 0:26
    change them after a user clicks something,
    which we'll see how to do soon, I promise.
  • 0:26 - 0:30
    Let's change the style of this heading.
  • 0:30 - 0:33
    If we did that in CSS,
    it would look like this--
  • 0:33 - 0:39
    `#heading` to select by ID,
    and then we'll say `color: orange`.
  • 0:39 - 0:42
    Ta da, it's orange, just like the cat.
  • 0:42 - 0:46
    Now, to do that in JavaScript,
  • 0:46 - 0:50
    we first find the heading element,
    which we have here.
  • 0:50 - 0:56
    Then, we're going to access
    its style attribute with `.style`.
  • 0:56 - 1:01
    Then, we access the property
    that we're interested in-- `color`--
  • 1:01 - 1:05
    and set it equal to the new value.
  • 1:05 - 1:11
    Let's delete the property in CSS to
    see if it worked. Yup, it worked.
  • 1:11 - 1:17
    Now, notice down here we've got two dots
    because we're actually accessing
  • 1:17 - 1:22
    two objects. One of them is the element
    object and the other is the style object
  • 1:22 - 1:27
    that contains all the styles for that
    element as different properties.
  • 1:27 - 1:32
    What if we also wanted to change the
    background color of that heading?
  • 1:32 - 1:38
    In CSS it would be
    `background-color: black;`
  • 1:38 - 1:41
    Let's try that in JavaScript. So
  • 1:41 - 1:49
    `headingEl.style.background-color
    = "black";`
  • 1:49 - 1:54
    Uh oh, we have an error.
    This is actually invalid JavaScript,
  • 1:54 - 1:57
    because property names
    can't contain hyphens.
  • 1:57 - 2:02
    Instead we need to convert this CSS
    property name to a form that's valid
  • 2:02 - 2:11
    JavaScript, which we do by camel-casing it.
    Remove the hyphen and capitalize the "c".
  • 2:11 - 2:17
    And let's go test it out by deleting this property here, and yep, it's still black.
  • 2:17 - 2:22
    Now that I'm getting fancy, I want
    to make the heading center aligned too.
  • 2:22 - 2:27
    So I will add one more line down here.
  • 2:27 - 2:34
    `headingEl.style.textAlign`--
    which we camel-case-- `= "center"`.
  • 2:34 - 2:38
    Once again, we camel-case it since it
    was two words with a hyphen before,
  • 2:38 - 2:45
    and now we've got this heading that looks
    like our cat and also like Halloween. Yay.
Title:
Changing CSS styles (Video Version)
Description:

more » « less
Video Language:
English
Duration:
02:46

English subtitles

Revisions