David Stockdale's Scrapcode

Embeddable Iframe

Here’s a simple bit of shortcode that creates a button which then displays an iframe (which you can use to show another page/post on your website):

/**
 * Adds shortcode (David Stockdale).
 */
add_shortcode( 'chatbot', 'chatbot_shortcode' );
/**
 * A button that loads the chat bot page (David Stockdale).
 * Shortcode should be something like this:
 * [chatbot]
 */
function chatbot_shortcode() {
	return <<<HTML
	<html>
	<body>
	<p id="botMsg">Click below to open iframe!</p>
	<button id="botBtn" onclick="choice1()">Open</button>
	<script type="text/javascript">
	function choice1(page)
	{
		var ifrm = document.createElement("iframe");
		ifrm.setAttribute("src", "YOUR URL HERE");
		ifrm.setAttribute("id", "framey");
		ifrm.style.width = "100%";
		ifrm.style.height = "400px";
		document.getElementById("botMsg").appendChild(ifrm);
		document.getElementById("botBtn").innerHTML = "Close";
		document.getElementById('botBtn').onclick = function() {
			//make it close chatbot
			document.getElementById("botMsg").removeChild(document.getElementById("framey"));
			document.getElementById("botBtn").innerHTML = "Open";
			document.getElementById('botBtn').onclick = function() {
				//and open again after closed
				var ifrm = document.createElement("iframe");
				ifrm.setAttribute("src", "YOUR URL HERE");
				ifrm.setAttribute("id", "framey");
				ifrm.style.width = "100%";
				ifrm.style.height = "400px";
				document.getElementById("botMsg").appendChild(ifrm);
				document.getElementById("botBtn").innerHTML = "Close";
				document.getElementById('botBtn').onclick = function() {
					//make it close chatbot
					document.getElementById("botMsg").removeChild(document.getElementById("framey"));
					document.getElementById('botBtn').remove();
				}
			}
		}
	}
	</script>
		</body>
	</html>
	HTML;
}

I have also made it so that the iframe can be opened and closed a few times with some quick and dirty code.

I’m sure there’s a better way to do it so it loops infinitely but I can’t find it right now.

Here’s it working:

Click below to open iframe!

If this helped you, leave a like or a comment!

Leave a Reply