I have some code that should dynamically load an iframe. The issue is i have a function that should make it cascade to the next id appended to the iframe. I need someone to help pinpont the issue with my code.
const $iframe = $("#content-frame");
$($iframe).attr('src', cath);
var cath = 'https://exanple.com' + myIds[i] + '/embed/dynamic?';
console.log(cath);
const myIds = ['1_aq4jiqb', '1_4u0ocu4u'];
function switchId() {
for (let i = 0; i < myIds.length; i++) {
cath = 'https://www.exanple.com' + myIds[i] + '/embed/dynamic?';
}
}
setInterval(function() {
switchId()
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<iframe id="content-frame" src="" width="400px" height="400px"></iframe>
This overwrites cath over and over again cath = 'https://www.exanple.com' + myIds[i] + '/embed/dynamic?'; and you are not using cath anywhere.
You do NOT want any other loop than what you get with setInterval
Also no need to cast a jQuery object to a jQuery object.
I wrap the list
const $iframe = $("#content-frame");
const myIds = ['1_aq4jiqb', '1_4u0ocu4u'];
let cnt = 0;
$iframe.on("load",function() { console.log($(this).attr("src"))})
setInterval(() => {
const url = 'https://www.example.com/' + myIds[cnt] + '/embed/dynamic?';
$iframe.attr('src', url);
cnt++;
if (cnt >= myIds.length) cnt = 0; // wrap the list
}, 3000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<iframe id="content-frame" src="" width="400px" height="400px"></iframe>
Same code without jQuery
const iframe = document.getElementById("content-frame");
const myIds = ['1_aq4jiqb', '1_4u0ocu4u'];
let cnt = 0;
iframe.addEventListener("load",e => console.log(e.target.src))
setInterval(() => {
const url = 'https://www.example.com/' + myIds[cnt] + '/embed/dynamic?';
iframe.src = url;
cnt++;
if (cnt >= myIds.length) cnt = 0; // wrap the list
}, 3000);
<iframe id="content-frame" src="" width="400px" height="400px"></iframe>
Only change iframe element SRC to solve the issue.
const myIds = ['1_aq4jiqb', '1_4u0ocu4u'];
let cnt = 0;
setInterval(function() {
const src = 'https://www.example.com/' + myIds[cnt] + '/embed/dynamic?';
document.getElementById('myIframe').src = src;
cnt++;
if (cnt >= myIds.length) cnt = 0;
}, 3000);