I have a fairly simple page with a sidebar nav and an iFrame in which to load content.
I want to change the content of the of the iFrame by clicking on links in the sidebar nav. I'm using the javascript to change the source (.src) of the document.element.
I've read numerous articles (StackOverflow) and the code should work, but is simply doesn't.
The code below is the html page I've created and it includes the JS in a tag.
Instead, do all your work in JavaScript and use .addEventListener() to set up event handlers.
Don't use a hyperlink when a button (or some other element) will do. If you do use a hyperlink, you need to disable its native desire to navigate, which is done by setting the href attribute to #, not "".
// Place this code into a <script> element that goes just before the closing body tag (</body>).
// Get a reference to the button and the iframe
var btn = document.getElementById("btnChangeSrc");
var iFrame = document.getElementById("contentFrame");
// Set up a click event handler for the button
btn.addEventListener("click", getContent);
function getContent() {
console.log("Old source was: " + iFrame.src);
iFrame.src="LoremIpsum.html";
console.log("New source is: " + iFrame.src);
}