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.
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<link href="css/default.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
function getContent{
document.getElementById("contentFrame").src="LoremIpsum.html";
}
</script>
</head>
<body>
<div class="sidebar"><h1>Technical Documentation</h1>
<ul>
<li>Configuration Guides</li>
<li>API Guides</li>
<li><a href="" onclick='getContent()'> LoremIpsum</a></li>
</ul>
<!-- <button onclick="getContent()">Lorem Ipsum</button> -->
</div>
<iframe class="content" id="contentFrame" src="dummy.html">
</iframe>
</body>
Your problem was that you forgot to add
()
after your function name.Beyond that, there are a few other things to correct:
Don't use inline HTML event attributes (
onclick
,onmouseover
, etc.) as they:this
binding in your callback functions.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""
.You have a syntax error in your function declaration (missing parenthesis):
Should be:
You also need to prevent the default event for the link
This is a syntax error. Parenthesis are required no matter the parameters of the function. However, it is a good practice to place script tags at the bottom of the body tag.
You can use javascript:void(0).
Or return false on javascript