javascripthtmlcssbuttoniframe

how to open different URLs in iframes using JavaScript and HTML buttons


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!


Solution

  • 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