javascripthtmlwindow-resizeresizable

Javascript event which occurs when resizing a DOM element?


Im working on a project in which the height value of a resizable div always needs to be divisible by 24 (This is so it always matches the default lineheight). I have created a function for resizing the div and i now need to run the function whenever the div is resized. Events that fire when the entire window is resized exist but im not able to find any events which fire when a specific DOM element is resized.

The following is my code:

HTML

<body>
    <div id="resizable-div" onresize="changeHeight()"></div>
<body>

Javascript

let resizeDiv = document.getElementById('resizable-div');

function changeHeight(){

  if (resizeDiv.style.height % 24 != 0) {
    resizeDiv.style.height = `${Math.round(resizeDiv.offsetHeight / 24) * 24}px`
  }
    
}

I was expecting the above code to change the height of resizable-div whenever it was resized. It doesn't, however when writing my code like this:

<body onresize="changeHeight()">
    <div id="resizable-div"></div>
<body>

It produces the outcome im looking for, but only whenever the size of the entire viewport is changed. How can i call my function whenever the height of my resizable-div changes?


Solution

  • After deciding to use my brain the solution was painfully simple. Since the div is resized by the user dragging it, i can simply add an event listener to the resizable-div which listens to the mouseup event. Here is the code:

    HTML

    <body>
        <div id="resizable-div"></div>
    <body>
    

    Javascript

    let resizeDiv = document.getElementById('resizable-div');
    
    function changeHeight(){
      if (resizeDiv.offsetHeight % 24 != 0) {
          resizeDiv.style.height = `${Math.round(resizeDiv.offsetHeight / 24) * 24}px`
      }
    }
    
    resizeDiv.addEventListener('mouseup', (event) => {
      changeHeight();
    })
    

    This will make the div snap to the closest height that is divisible by 24 whenever the user stops dragging it.