Home > Software engineering >  Changing Iframe size by click event listener not working
Changing Iframe size by click event listener not working

Time:04-24

I'm trying to change the iframe size by clicking the button by using the click event listener. But the iframe auto runs the function and I haven't even clicked the button...

Someone said this is a duplicate of How to pass arguments to addEventListener listener function? but I don't see where is this even related???

const btn = document.querySelector('button');
const iframe = document.querySelector('iframe');

function change(w) {
   iframe.style.width = `${w}px`;
}

btn.addEventListener('click', change(150));
iframe {
  width: 300px;
  height: 300px;
  background-color: blue;
}
<button>Change</button>
<iframe src=""></iframe>

CodePudding user response:

change your event listener function like so

btn.addEventListener('click', () => change(150));

OR

btn.addEventListener('click', function() { change(150) });

addEventListener expects a function definition and not a function call as second argument.

For more read: https://www.w3schools.com/js/js_htmldom_eventlistener.asp

  • Related