Reputation: 749
So I want to make a small website with a menu that has four HTML buttons. Instead of the buttons opening a completely new website I just want an iframe tag to change the URL it's displaying according to the buttons that are pressed.
Please keep it simple, I am a beginner in HTML, JS and CSS. Thanks!
Upvotes: 5
Views: 27161
Reputation: 271
You just need to get the iframe
element with Javascript and change the src
attribute
The question has already been answered here : https://stackoverflow.com/a/6001043/7988438
var frame = document.getElementById("frame");
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
var btn3 = document.getElementById("btn3");
btn1.addEventListener("click",link1)
btn2.addEventListener("click",link2)
btn3.addEventListener("click",link3)
function link1(){
frame.src="https://pixabay.com/photo-2845763/"
}
function link2(){
frame.src="https://pixabay.com/photo-3126513/"
}
function link3(){
frame.src="https://pixabay.com/photo-3114729/"
}
<button id="btn1" >link1</button>
<button id="btn2" >link2</button>
<button id="btn3" >link3</button>
<iframe id="frame" src="https://pixabay.com/photo-2845763/"></iframe>
EDITED to take comment into consideration
Upvotes: 9
Reputation: 41
You can use the target attribute of an anchor tag, to tell the link to load in the iframe. I think that's the simplest way.
<iframe src="http://page1.html" id="frame1" name="frame1"></iframe>
<a href="http://page2.html" target="frame1">click here for page 2</a>
Upvotes: 4
Reputation: 454
You can do this by having a function that changes the src attribute of the iframe.
<iframe src="http://cbc.ca/" id="theiframe" width="500" marginwidth="0" height="500" marginheight="0" align="middle" scrolling="auto"></iframe>
<button onclick="loadnewpage('http://bbc.com')">BBC Page</button>
<button onclick="loadnewpage('http://cbc.ca')">CBC Page</button>
<script>
function loadnewpage(newsrc){
var newloc = newsrc;
document.getElementById('theiframe').setAttribute('src', newloc);
}
</script>
Check out JS function paramaters and arguments to learn more about how this works
Upvotes: 5