Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #dynamically #HowTo

How to change height of div dynamically in javascript?

In this article, you will learn how to dynamically change the height of a <div> element using JavaScript.

Whether you need to adjust the height of a div based on user interaction or other dynamic factors, these methods can be used. Let's dive in!

Changing the Height Using the style Property #

One way to modify the height of a <div> element dynamically is by directly manipulating its style property in JavaScript.

<div id="myDiv" style="height: 100px; background:red"></div>
<button onclick="changeHeight()">Change Height</button>

<script>
  function changeHeight() {
    const div = document.getElementById("myDiv");
    div.style.height = "200px";
  }
</script>

Explanation of the above example:

  1. We have an initial <div> with an id of myDiv and a predefined height of 100 pixels.
  2. A button is included with an onclick event handler, triggering the changeHeight() function.
  3. Inside the function, we select the div element by its ID and change its style.height property to the desired value (in this case, 200 pixels).

Using CSS Transitions for Smooth Height Changes #

To achieve smoother height transitions, we can utilize CSS transitions along with JavaScript.

<div id="myDiv" class="transition-div"></div>
<button onclick="toggleHeight()">Toggle Height</button>

<style>
  .transition-div {
    height: 100px;
    background-color: red;
    transition: height 0.3s ease;
  }
  .expanded{
      height: 250px;
  }
</style>

<script>
  function toggleHeight() {
    const div = document.getElementById("myDiv");
    div.classList.toggle("expanded");
  }
</script>

Explanation:

  1. We have a <div> element with the class transition-div and an initial height of 100 pixels. We define a CSS transition property for height changes to make them smooth.
  2. The button triggers the toggleHeight() function when clicked.
  3. Inside the function, we toggle the expanded class on the div, which changes its height based on the CSS rule, providing a smooth transition effect.

Conclusion #

In this article, we've explored two methods to dynamically change the height of a <div> element in JavaScript.

You can use the direct style property manipulation for quick adjustments or implement CSS transitions for smoother height changes with animations.

save
listen
AI Answer
Write Your Answer
loading
back
View All