I have a main (parent) page that hosts 3 iframes that are under the same domain. The iframe's src attribute is added on a click event, so the iframe's aren't loaded until needed.
What I want is when I click a certain div on my main page, it will trigger a click on a specific div that's located inside all 3 iframes at the same time.
I have tried the following code in my parent page:
function myFunction() {
var iframe = document.getElementById("iframe1");
var elmnt = iframe.contentWindow.document.getElementById("btn").click()
}
and repeated it twice more for iframe's #iframe2
and #iframe3
. However, it didn't work unless I loaded the iframes in order that they're written on my page. (i.e the click event on #iframe2
didn't execute until after #iframe1
's event). This is a problem as I'm unable to control what iframe visitors will load first. I tried giving them separate function() names, but the same thing occurred - only one iframe was effected at a time. Note, this worked fine when I tested it out with the iframe's already having their src's like normal, just not when they're added manually.
I also tried adding this in the iframe pages:
parent.document.getElementById('btn').onclick = function(){
document.getElementById('btn').click();
}
However, this only works on the first iframe that is loaded (i.e if #iframe2
is loaded first, then the iframe1
's and iframe3
's event wont execute)
Is there any other solutions I could try? My purpose is creating a day and night toggle with classList.toggle
, and I want all the iframes
css to be toggled at the same time, with the toggle button
being on the main page.
(I prefer vanilla javascript for my main page, but am fine with jQuery on the iframe pages)