OiO.lk Blog HTML How to change width and height of iframe tag dynamically?
HTML

How to change width and height of iframe tag dynamically?


My <iframe> tag contains a chat widget; that chat widget contains a button that shows and hide chat inbox. How do I modify it so that it changes its width and height according to if the inbox is visible or not?

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
   
    <title>Parent Page</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="box">
      <p style="color: white; font-size: 50px">This is the HTML page</p>
    </div>

    <iframe src="http://localhost:5010/widget" id="target"></iframe>
  </body>
</html>

CSS

.box {
  width: 500px;
  height: 500px;
  background-color: brown;
}

#target {
  position: fixed;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background-color: red;
  border: none;
  width: 350px;
  height: 100%;
}

Here is the screen shot of chat widget – click here

I tried using this way but it doesn’t work

window.addEventListener("message", function (event) {
        console.log("message event fired");

        const iframe = document.getElementById("target");
        const { width, height } = event.data;

        if (width && height) {
          iframe.style.width = width + "px";
          iframe.style.height = height + "px";
        }
      });



You need to sign in to view this answers

Exit mobile version