110 likes | 124 Vues
Learn how to modify CSS styles in a document using Javascript. Discover how to alter the style for a specific element, change classes, and use timeouts and intervals for dynamic modifications. Get ready to add animations to your webpages!
E N D
Regularly scheduled events and JS+CSS Things are gonna get animated
But first… • Any questions on your current homework assignment?
Today • How to use Javascript to modify the CSS styles in a document • How to get a function to be called on a regular basis or after a delay
Modifying CSS in Javascript • Javascript gives us the ability to modify CSS as we're looking at the webpage • Two methods we'll talk about today: • Changing the style for a single, specific element • Changing the classes associated with a single, specific element
HTMLElement.style • For any HTMLElement, we can modify the "style" attribute to adjust the CSS styles • HTMLElement.style.setProperty("background-color", "#03ba12"); • HTMLElement.style.getPropertyValue("margin-left"); • HTMLElement.style.removeProperty("line-height"); • HTMLElement.style.borderBottomWidth = "12px";
Aside: the transition property • The transition property allows us to specify how properties behave when they are changed • We can use this to make things like background colors change smoothly • Syntax: • transition: property duration • Property is any css property, or "all" (no quotes) • Duration is a number of seconds or milliseconds such as 1s, .5s, 150ms, etc. • Let's try this out…
HTMLElement.classList • The classList attribute allows us to modify the list of CSS classes associated with a given element • Remember, each element can belong to multiple CSS classes • HTMLElement.classList.add("funClass"); • HTMLElement.classList.remove("boringClass"); • HTMLElement.classList.toggle("somethingElse"); • HTMLElement.classList.contains("emph");
Timeouts and Intervals • Timeouts and intervals are two ways that we can arrange to have a function called in the future • Timeout: call a specified function once at a certain point in the future • Interval: call a specified function repeatedly after a delay given in milliseconds
Timeouts • setTimeout(func, delay) or setTimeout(func) • Calls the function "func" after delay milliseconds, or zero ms if using the second form • The function will not be run immediately, but will instead run as soon as it can after the timer expires • The return value can later be passed to clearTimeout() to cancel the timeout from happening • Let's see an example and then use setTimeout along with a classList for some fun…
Intervals • setInterval(func, delay) • Will call the function "func" every delayms • The return value can later be passed to clearInterval to cancel the recurring function call • We can setInterval to do some amusing things…