WordPress: How to create an iframe refresh button

Let’s say you have an interactive canvas loaded in an iframe and you want to have the ability to “clear” the canvas without reloading the entire page. This example was created using p5.js and the html was loaded into an iframe. After drawing on this canvas, it can be cleared by clicking the “Clear Canvas” button below.

 

The separate parts that make this work are:

1. Load the canvas into an iframe. Notice the name="square_canvas". This ties the name given to the iframe to the name of the page element used in the JavaScript function described in steps 2 and 3. For example:

[ iframe name="square_canvas" src="http://bluegalaxy.info/processing/p5/square_canvas/" scrolling="no" width="640" height="400" id="iframe_drop_shadow" ]

2. Add JavaScript to the body of the post. This JavaScript code consists of a single function that will clear the iframe canvas.

<script language="JavaScript">
function refreshIframe(name) {
    var ifr = document.getElementsByName(name)[0];
    ifr.src = ifr.src;
}
</script>

3. Create the “Clear Canvas” button. Notice the class="btn". Also, pass the name of the iframe “square_canvas” to the refreshIframe() JavaScript function via onClick.

<button class="btn" onclick="refreshIframe('square_canvas');">Clear Canvas</button>

4. Add custom CSS to the WordPress theme. This is the CSS for the button class “btn”. For details about how to add custom CSS, see this post. Here is the CSS that was used to create the “Clear Canvas” button:

.btn {
  -webkit-border-radius: 8;
  -moz-border-radius: 8;
  border-radius: 8px;
  -webkit-box-shadow: 0px 2px 5px #666666;
  -moz-box-shadow: 0px 2px 5px #666666;
  box-shadow: 0px 2px 5px #666666;
  font-family: Arial;
  color: #ffffff;
  font-size: 14px;
  background: #0369ad;
  padding: 7px 15px 7px 15px;
  text-decoration: none;
}

.btn:hover {
  background: #299be6;
  text-decoration: none;
}

 

Leave a Reply