Lecture Notes On Day 22
JavaScript and CSS Interactions
Introduction
JavaScript can be used to
dynamically interact with CSS, allowing web pages to update and change styles
based on user actions or events. This interaction adds interactivity, making
websites more dynamic and engaging. Today, we will explore how to change element
styles with JavaScript, toggle classes dynamically, and create animations using
JavaScript.
1.
Changing Element Styles with JavaScript
One of the most basic ways
JavaScript interacts with CSS is by directly changing the style of an element.
JavaScript provides access to the style property of DOM (Document Object Model)
elements, which can be used to modify the inline styles of an element.
Accessing
and Modifying Inline Styles
JavaScript allows you to
manipulate CSS properties directly by using the style property on a DOM
element. Each style property in CSS is represented by a corresponding property
in JavaScript, but with camelCase syntax instead of kebab-case.
For example, to modify the
background color and font size of an element, you can use the following code:
|
<!DOCTYPE html> <html
lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Change Styles with JavaScript</title> </head> <body> <div
id="myElement">Hello, World!</div> <button
onclick="changeStyle()">Change Style</button> <script>
function changeStyle() {
const element = document.getElementById("myElement");
element.style.backgroundColor = "yellow"; // Change
background color
element.style.fontSize = "30px"; // Change font size
element.style.color = "red"; // Change text color } </script> </body> </html> |
Explanation:
- The
getElementById method is used to select the element with the id of
myElement.
- The
style property allows you to modify the inline styles. The
backgroundColor, fontSize, and color properties are set directly.
Important Notes:
- Only
inline styles can be modified through this method (i.e., styles set
directly on an element).
- You
cannot change styles that are defined in external stylesheets unless those
styles are specified as inline styles or through class manipulation.
2.
Toggling Classes with JavaScript
Instead of directly changing
individual CSS properties, JavaScript can also interact with CSS by adding,
removing, or toggling classes on elements. This is a more powerful and
maintainable method because it allows for pre-defined styles in your CSS files.
Using
classList to Toggle Classes
The classList property in
JavaScript provides methods to add, remove, or toggle CSS classes on elements.
- add():
Adds a class to an element.
- remove():
Removes a class from an element.
- toggle():
Toggles a class on an element (adds the class if it doesn't exist, removes
it if it does).
For example, let's create a
button that toggles a class to change the background color of a div:
|
<html
lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Toggle Class with JavaScript</title> <style>
.highlight {
background-color: yellow; } </style> </head> <body> <div
id="myElement">Click the button to change my background
color!</div> <button
onclick="toggleClass()">Toggle Highlight</button> <script>
function toggleClass() {
const element = document.getElementById("myElement");
element.classList.toggle("highlight"); } </script> </body> </html> |
Explanation:
- The
toggleClass function is called when the button is clicked.
- The
classList.toggle("highlight") method toggles the highlight
class. If the class is not already applied, it is added; if it's already
applied, it is removed.
Advantages of Using Classes:
- Keeps
your JavaScript cleaner and separate from styles.
- Allows
you to take advantage of CSS transitions and animations for smoother
effects.
3.
Animating Elements with JavaScript
JavaScript can also be used to
create animations by manipulating CSS properties over time. One common method
for creating animations with JavaScript is using the setInterval() or
requestAnimationFrame() methods to repeatedly change the styles of an element.
Using
setInterval() to Animate an Element
The setInterval() method can be
used to change the style of an element over time. It repeatedly executes a
function at specified intervals (in milliseconds).
Here is an example of moving a
box across the screen using setInterval():
|
<!DOCTYPE html> <html
lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Animate with JavaScript</title> <style>
#myBox {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
top: 50px;
left: 0px; } </style> </head> <body> <div
id="myBox"></div> <button
onclick="startAnimation()">Start Animation</button> <script> let
position = 0;
function startAnimation() {
const element = document.getElementById("myBox");
setInterval(function() {
position += 5; // Move the box 5px every interval
element.style.left = position + 'px'; // Update the position of the box
if (position >= window.innerWidth - 100) {
position = 0; // Reset position when the box reaches the right side of
the screen
}
}, 50); // Execute every 50 milliseconds } </script> </body> </html> |
Explanation:
- The
setInterval() function moves the box to the right by 5px every 50
milliseconds.
- The
box resets its position once it reaches the right side of the screen.
Using
requestAnimationFrame() for Smoother Animations
requestAnimationFrame() is a
better alternative to setInterval() for animations because it syncs with the
browser's refresh rate, resulting in smoother animations. It's particularly
useful for animations that need to run in real-time.
Here's an example of how you can
animate the position of an element using requestAnimationFrame():
|
<html
lang="en"> <head> <meta
charset="UTF-8"> <meta
name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Animate with requestAnimationFrame</title> <style>
#myBox {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50px;
left: 0px; } </style> </head> <body> <div
id="myBox"></div> <button
onclick="startSmoothAnimation()">Start Smooth
Animation</button> <script> let
position = 0;
function animate() {
const element = document.getElementById("myBox");
position += 5;
element.style.left = position + 'px';
if (position < window.innerWidth - 100) {
requestAnimationFrame(animate);
} }
function startSmoothAnimation() {
animate(); // Start the animation using requestAnimationFrame } </script> </body> </html> |
Explanation:
- requestAnimationFrame(animate)
calls the animate() function before the next repaint, ensuring smooth
movement.
- The
animation continues as long as the position is less than the width of the
window.
Conclusion
In this lesson, you learned how
JavaScript can interact with CSS to:
1. Change
element styles dynamically using JavaScript's style property.
2. Toggle
CSS classes using the classList API, which allows for easy
style changes without directly manipulating inline styles.
3. Animate
elements with JavaScript by using setInterval() or requestAnimationFrame(),
providing real-time dynamic styling and movement.
