Do you want to know how to reload iFrame by clicking on a button or by listening to any other events?

By using a few lines (4-6 lines) of JavaScript, you can easily create a function to reload an iFrame's content.

how to center iframe

If you are totally new to JavaScript, then do not worry because I’m going to explain each and every method so that a newbie can also understand.

First, you need to add the iFrame which you want to reload when an event occurs on the website, you can use our iFrame Generator tool to generate a fresh iFrame code.

I’m assuming you already added the iFrame code to your HTML file, if you haven’t then do it and follow the next steps.

Now add an ID to your iFrame so that you can easily select the iFrame in the JavaScript file.

<iframe id="your-iframe-id" src="your_url_here"></iframe>

Once you add the ID, Now add a <script> tag into your HTML file.

<script></script>

Inside the <script> tag, create a function. You can name the function anything you want. In my case, I'm naming it “reloadIframe”.

<script>
        function reloadIframe() {
                </script>

        }

Once you've created the function, select the iFrame inside the function and store it in a variable. You can use the getElementById method to select the iFrame.

<script>
        function reloadIframe() {
      var iframe = document.getElementById('your-iframe-id');
               </script>}

Now create another variable where we need to store the source of the iFrame.

var iframeSrc = iframe.src;

In the third step, assign the same src value back to the iframe's src attribute.

<script>
        function reloadIframe() {
      var iframe = document.getElementById('your-iframe-id');
      var iframeSrc = iframe.src;
               </script>}

This method utilizes the src attribute of the iFrame to trigger a reload. By assigning the same src value, the iFrame's content will refresh, effectively reloading the iFrame.

Now, in the final step, add the function to the button or anywhere you want to call the function. In the example, I want to reload the iFrame when someone clicks on a button, so I’m going to add the function to a button.

 <button onclick="reloadIframe()">Reload</button>
<script>
  function reloadIframe() {
    var iframe = document.getElementById('your-iframe-id');
    var iframeSrc = iframe.src;
    iframe.src = iframeSrc;
  }
           <script>

When someone clicks on the button, the iFrame will reload.

I hope by reading this post, you now know how to reload an iFrame using JavaScript. If you like this post, then do share it with your friends.