Home >Web Front-end >CSS Tutorial >How to Dynamically Modify CSS Styles with JavaScript Event Listeners?

How to Dynamically Modify CSS Styles with JavaScript Event Listeners?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-23 08:06:34739browse

How to Dynamically Modify CSS Styles with JavaScript Event Listeners?

How to Dynamically Modify CSS Styles with JavaScript

To dynamically change the CSS properties of an element using JavaScript, several methods can be employed. One of the most versatile approaches is to use the style property of the element. This property provides access to all inline styles defined for the element.

Consider the following HTML and CSS snippet:

<div class="left">
  Hello
</div>
<div class="center">
  <div class="left1">
.left,
.right {
  margin: 10px;
  float: left;
  border: 1px solid red;
  height: 60px;
  width: 60px;
}

.left:hover,
.right:hover {
  border: 1px solid blue;
}

.center {
  float: left;
  height: 60px;
  width: 160px;
}

.center .left1,
.center .right1 {
  margin: 10px;
  float: left;
  border: 1px solid green;
  height: 60px;
  width: 58px;
}

In this snippet, we have three elements (left, center, and right), each with different classes. When the left or right elements are hovered over, they change their border color to blue.

To make the left1 element appear when left is hovered and right1 when right is hovered, we can use JavaScript:

document.querySelector('.left').addEventListener('mouseenter', () => {
  document.querySelector('.left1').style.display = 'block';
});

document.querySelector('.left').addEventListener('mouseleave', () => {
  document.querySelector('.left1').style.display = 'none';
});

document.querySelector('.right').addEventListener('mouseenter', () => {
  document.querySelector('.right1').style.display = 'block';
});

document.querySelector('.right').addEventListener('mouseleave', () => {
  document.querySelector('.right1').style.display = 'none';
});

In this JavaScript code, we use the addEventListener method to attach event listeners to the left and right elements for the mouseenter and mouseleave events. When the mouse enters the element, the corresponding hidden element is made visible by changing its display style to block. When the mouse leaves the element, the hidden element is again hidden.

Using the style property to dynamically change CSS properties gives you great flexibility in modifying the appearance of elements in your web pages.

The above is the detailed content of How to Dynamically Modify CSS Styles with JavaScript Event Listeners?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn