I have a relatively simple demo here where I have two embed elements with the same class, and upon page load one is set to display and the other is not. I'm calling a function and setting an interval for every 5 seconds starting on page load which should toggle the display rules for the classes (only one embed element should show at a time and then they should alternate on the timer).
I have border colors on the embed elements for testing, but it seems like neither element is showing on page load once I added the second 'if' statement in the JS
What am I doing wrong
window.onload = function () {
test();
setInterval(function() {
test();
}, 5000);
}
function test(){
console.log('starting');
var all = document.getElementsByClassName('pdfEmbed');
for (var i = 0; i < all.length; i ) {
if(all[i].style.display = "none"){
all[i].style.display = "block";
}
if(all[i].style.display="block"){
all[i].style.display = "none";
}
}
}
<embed class="pdfEmbed" src="#" style="margin-top: 40px;position:absolute; display: block; left: 0; top: 0; border: 1px solid red;" width="100%" height="100%" type="application/pdf">
<embed class="pdfEmbed" src="#" style="margin-top: 40px;position:absolute; border: 1px solid black; display: none; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Here's what's happening with the second if
:
// set current child display to "block" if it is "none"
if(all[i].style.display = "none"){
all[i].style.display = "block";
}
// the check is always true, since you just set the display to "block"
if(all[i].style.display="block"){
// therefore, for all elements set display to none
all[i].style.display = "none";
}
The fix is easy: Use an else if
instead of the second if
. In case you only want to have the two display states "none" and "block", an else
is enough.
EDIT: I just noticed a second error. You have to use comparison (==
or ===
) instead of assignment (=
) in your if
conditions. So this should be working:
if(all[i].style.display == "none") {
all[i].style.display = "block";
} else {
all[i].style.display = "none";
}
CodePudding user response:
var last_index = 0;
function test() {
var e = document.querySelectorAll(".pdfEmbed");
for (var k = 0; k < e.length; k ) {
e[k].style.display = k == last_index ? "block" : "none";
}
last_index ;
if (last_index >= e.length) { last_index = 0; }
}