0

I made a module that creates and initialises an element and returns it to the application. The application will then attach it to the DOM.

I would like to register (during initialisation) an event that is fired when the width of the element changes. I know you can use window.resize to receive an event when the window is resized and probably also the width of the element but the width also changes when it is added to the DOM (before adding it is 0). Anyone?

Tin
  • 699
  • 1
  • 6
  • 19
  • What have you tried already? ([Hint](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events): `elem.dispatchEvent(new Event('arbitrary'));` ) – Tibrogargan Apr 25 '19 at 05:29

2 Answers2

1

Here is you can check element resize event

Reference: https://stackoverflow.com/a/39312522/4286794

function outputsize() {
 width.value = textbox.offsetWidth
 height.value = textbox.offsetHeight
}
outputsize()

new ResizeObserver(outputsize).observe(textbox)
Width: <output id="width">0</output><br>
Height: <output id="height">0</output><br>
<textarea id="textbox">Resize me</textarea><br>
Parth Jasani
  • 2,349
  • 1
  • 19
  • 26
0

You can use the "width" function of jquery to get the width of the element.

<script>
  $("button").click(function(){
  alert("Width of div: " + $("div").width());
  });
</script>   

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
  $("button").click(function(){
    alert("Width of div: " + $("div").width());
  });
});
</script>
<div style="height:100px;width:300px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div><br>

<button>Display the width of div</button>

</body>
</html>
Prasad Supare
  • 48
  • 1
  • 8
  • In your example the element is already added to the DOM. Then indeed the width is known. – Tin Apr 25 '19 at 06:00
  • okay so if you want to get the width of the element whenever it gets added then you could add the ".width()" inside jquery's "setInterval" function so you'll be constantly getting the width of the element. . setInterval(function(){ console.log("Width of div: " + $("div").width()); }, 3000); – Prasad Supare Apr 25 '19 at 06:05