So I have five different div containers, and one iframe. I need to change src of iframe depending on which div I click. They're youtube links, so each time I click on particular div, iframe src should be changed. Divs, clicking on which iframe should be changed:
Html code of iframe:
<div class="full">
<iframe id="iframe" class="responsive_frame" src="https://www.youtube.com/embed/K0u_kAWLJOA"></iframe>
</div>
I've found some kind of solution, but it doesn't seem to work:
var locations = ["https://www.youtube.com/embed/K0u_kAWLJOA",
"https://www.youtube.com/embed/c7nRTF2SowQ",
"https://www.youtube.com/embed/6LOD-pwJY6E",
"https://www.youtube.com/embed/8X2kIfS6fb8",
"https://www.youtube.com/embed/p5yUKjOOWvM"
];
var currentIndex = 0;
var len = locations.length;
$(document).ready(function(){
$(document).on('click', '.preview', function(){
currentIndex = this.attr("id") == "1" ?
currentIndex < len - 1 ? currentIndex : 0 :
currentIndex > 0 ? --currentIndex : len - 1;
$('#iframe').attr('src', locations[currentIndex]);
});
})
So basically, div has preview class, so jquery should activate a function when div with .preview class is clicked, and then, given IDs of divs, it should change the src of iframe, but it doesn't seem to work.
Edit: Ok, so i made a completely new page and tried @Rana method, and it still didn't work in my browser, so i went to console and next errors showed up there:
So I'm not sure, maybe it has something to do with loading youtube links from javascript code?
CodePudding user response:
Here is a working example of changing src
on click of buttons and every time changed src
is displayed.
- First
src
values are provided in aarray
- Now looped through all the tags with class
.srcChanger
and added event listener which actives onclick
. - Then function is executed which takes value from
array
according toi
th value of tag
var locations = ["https://www.youtube.com/embed/K0u_kAWLJOA",
"https://www.youtube.com/embed/c7nRTF2SowQ",
"https://www.youtube.com/embed/6LOD-pwJY6E",
"https://www.youtube.com/embed/8X2kIfS6fb8",
"https://www.youtube.com/embed/p5yUKjOOWvM"
];
var btnSrc = document.getElementsByClassName("srcChanger");
for (let i = 0; i < btnSrc.length; i ) {
btnSrc[i].addEventListener('click', function() {
document.getElementsByClassName("responsive_frame")[0].src = locations[i];
document.getElementById("demo").innerHTML = locations[i];
})
}
<div class="full">
<iframe id="iframe" class="responsive_frame" src="https://www.youtube.com/embed/K0u_kAWLJOA"></iframe>
</div>
<button class="srcChanger">Btn1</button>
<button class="srcChanger">Btn2</button>
<button class="srcChanger">Btn3</button>
<button class="srcChanger">Btn4</button>
<button class="srcChanger">Btn5</button>
<div id="demo"></div>