How can I create a variable visibility in an iframe to hide it and display a static image if the iframe shows an error message when loading a specific website?

Published on
September 22, 2023

To create variable visibility in an iframe and display a static image if the iframe shows an error message when loading a specific website, you can follow these steps:

  1. Add an iframe element to your webpage: Open your Webflow project and navigate to the page where you want to add the iframe. Drag and drop an Embed element from the Elements panel onto your page.

  2. Set the source URL for the iframe: In the settings of the Embed element, paste the URL of the website you want to display inside the iframe. Make sure that the URL is accessible and does not have any issues that would prevent it from loading properly.

  3. Create a custom code snippet: To handle the visibility of the iframe, you'll need to add a custom code snippet to your project. Go to the Custom Code section in the Project Settings of your Webflow project and add the following code:

<script>  window.addEventListener('DOMContentLoaded', function() {    var iframe = document.querySelector('iframe');    var fallbackImage = document.querySelector('.fallback-image');    iframe.addEventListener('load', function() {      iframe.style.display = 'block';      fallbackImage.style.display = 'none';    });    iframe.addEventListener('error', function() {      iframe.style.display = 'none';      fallbackImage.style.display = 'block';    });  });</script>
  1. Add a fallback image: Create or upload an image that you want to display if the iframe encounters an error. Drag and drop an Image element onto your page, position it where you want the fallback image to appear, and give it a class name, e.g., "fallback-image". You can style this image element however you like using the Webflow designer.

  2. Set initial visibility: By default, ensure that the iframe is hidden (display set to "none") and the fallback image is visible (display set to "block") in the Style panel.

Now, if the iframe encounters an error while loading the specified website, it will automatically hide the iframe and display the fallback image instead. Conversely, if the iframe successfully loads the target website, it will become visible, and the fallback image will be hidden.

Additional questions:

  1. How can I add an iframe to my Webflow project?
  2. What is the purpose of the "DOMContentLoaded" event in the code snippet?
  3. Can I use dynamic content for the fallback image in the iframe visibility setup?