Loading and unloading iframes with jQuery

In an older post I explained how to dynamically load iFrames with Javascript. Here
After using this method many many times, I think i've found a better way.

With jQuery!

First we need some things. First a <div> in the html

<div id="widget2"></div>

Now we need to implement the jQuery Library

  <script src="js/jQuery.js" type="text/javascript"></script>

Lets start our script. I will leave this in two functions, you could always run onLoad.

<script>
//create function
function createwidgetforecast(){  // function name

$("<iframe></iframe>").attr('id','widget2' ).appendTo('body');  // here we make an iframe with id appending it to the body

$("#widget2").attr('src','Widget/WeatherWidget/WeatherWidget.html').appendTo('widget2');  // append url

$("#widget2").attr('style','border:none;width:320px;z-index:2;height:480px;display:inline-block;position:absolute;' ).appendTo('widget2');  // append css styles

}

Thats it, you could add onClick to the div like so

<div id="importediframe"onclick="createwidgetforcast();">iFrame</div>

With this when you click on iFrame it will then load the iFrame


To remove the iframe its as simple as.

function removewidgetforecast(){
   $("#widget2").remove();
}


This is how LockBuilder loads lockscreens into itself. Also is how widgets are loaded and unloaded.

UPDATE!
This method leads to one small issue. White flicker when iFrame loads. This is my work around.

First I add visibility:hidden; to the appending css.

$("#widget2").attr('style','width:320px;height:480px;z-index:2;position:absolute;visibility:hidden;border:none;' ).appendTo('widget2');

Then I want to create a function that shows it.

For this I just append an onload function to the widget.
$("#widget2").attr('onLoad','visible()' ).appendTo('widget2'); }


Then I call a function that shows the element. No white flicker;)

function visible(){
  $("#widget2").css('visibility', 'visible');
}



JunesGraphics

No comments:

Post a Comment