'How to change iframe src when a button is pressed
I tried to change src of an iframe, to change trailers, but after trying to utilize the answer of a different post: iframe src change on button click but I still couldn't get it to work, it keeps saying: "newSrc is not defined at HTMLButtonElement.onclick (index)(9:65)"
I want to thank everyone for their comments, I found the problem and solved it, I forgot to link the javascript on the page I was working on, the dumbest mistake that I could've made
Thank you Chris for helping with extra tips and Nermin for making me realise my dumb mistake
function newSrc() {
var e = document.getElementById("Menu_trailers");
var newSrc = e.options[e.selectedIndex].value;
document.getElementById("trailers").src=newSrc;
}
<figure class="trailer">
<iframe src="https://www.youtube.com/embed/sfAc2U20uyg" id="trailers"> </iframe>
</figure>
<section class="button_trailer">
<select id="Menu_trailers">
<option value="https://www.youtube.com/embed/sfAc2U20uyg">Trailer 1</option>
<option value="https://www.youtube.com/embed/o-L1mMZ31hM">Trailer 2</option>
</select>
<button onclick="newSrc();" class="button_next_trailer">Change trailer</button>
</section>
Solution 1:[1]
Here is the JS code to get the src from the select menu, then set it to the iframe element
function newSrc() {
// Get The Select Menu Element
var e = document.getElementById("Menu_trailers");
// Set Select Menu Value (Selected Option) To Be The src Of The iframe
document.getElementById("trailer").src = e.value;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | salahineo |
