Isabel Cariod
Isabel Cariod

Reputation: 363

iframe javascript after onload

When iframe is loading I use a css class 'active' when is stop loading I switch to 'inactive' class.

<script type="text/javascript">
function frameload(){
    document.getElementById("loadnav").className = "active";
}
document.getElementById("loadnav").className = "inactive";
</script>
<iframe src="https://www.wikipedia.org/" onload="frameload()"></iframe>

The problem is that after loading does not return to 'inactive'.

Upvotes: 0

Views: 490

Answers (2)

Steven Kaspar
Steven Kaspar

Reputation: 1187

Couple things

  1. You don't have an id on your iframe so document.getElementById won't do anything

  2. There needs to be some listener for DOMContentLoaded because document.getElementById("loadnav").className = "inactive"; is trying to run before the iframe is actually on the page

iframe {
width: 100%;
height: 100%;
}
iframe.inactive {
border: 2px solid red;
}
iframe.active {
border-color: green;
}
<script>
function frameload(){
    document.getElementById("loadnav").className = "active";
}
function init(){
  document.getElementById("loadnav").className = "inactive";
  document.getElementById("loadnav").addEventListener('load', frameload);
}

document.addEventListener('DOMContentLoaded', init);

</script>

<iframe src="https://www.wikipedia.org/" id='loadnav'></iframe>

Upvotes: 1

Mouaici_Med
Mouaici_Med

Reputation: 410

are you tried to use jQuery. the instruction document.getElementById("loadnav").className = "inactive"; is executed after the loading the iframe

$('iframe').load(function() {
 document.getElementById("loadnav").className = "inactive";
});

Upvotes: 1

Related Questions