Events - Changing CSS through JavaScript

In web development, manipulating CSS styles dynamically is a common task, often achieved using JavaScript. One powerful aspect of JavaScript is its ability to respond to various events, such as clicks, hovers, or form submissions, and then modify the CSS styles of HTML elements accordingly. This documentation will explore how to change CSS styles through JavaScript by leveraging different events.

Prerequisites:

  • Basic understanding of HTML, CSS, and JavaScript.

  • Text editor or integrated development environment (IDE) for coding.

Steps:

Step 1: HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Manipulation with JavaScript</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div id="targetElement">This is the target element</div>
    <button id="changeColorBtn">Change Color</button>
    <script src="script.js"></script>
</body>
</html>

Step 2: CSS Styles (styles.css)

#targetElement {
    width: 200px;
    height: 100px;
    background-color: lightblue;
    text-align: center;
    line-height: 100px;
}

#targetElement.red {
    background-color: tomato;
}

#targetElement.blue {
    background-color: dodgerblue;
}

Step 3: JavaScript Logic (script.js)

// Get reference to the target element and the button
const targetElement = document.getElementById('targetElement');
const changeColorBtn = document.getElementById('changeColorBtn');

// Function to change color
function changeColor() {
    // Toggle class to change color
    targetElement.classList.toggle('red');
}

// Event listener for button click
changeColorBtn.addEventListener('click', changeColor);

Explanation:

  • HTML Structure: We have a div element with the id "targetElement" and a button with the id "changeColorBtn". We also link our external CSS file and JavaScript file.

  • CSS Styles: We define the initial styles for the target element (#targetElement) and two additional classes (red and blue) to change its background color.

  • JavaScript Logic:

    • We get references to the target element and the button using document.getElementById.

    • We define a function changeColor to toggle the class of the target element, which changes its background color.

    • We add an event listener to the button. When the button is clicked, the changeColor function is called, resulting in a change of the target element's color.

Conclusion: This documentation demonstrates how to change CSS styles through JavaScript by responding to events. By following these steps, you can dynamically manipulate the appearance of HTML elements based on user interactions or other triggers. Experiment with different events and CSS properties to create engaging and interactive web experiences.

Last updated