I have a simple iframe that I want to refresh every 5 seconds, without clicking somewhere or doing something at all
<iframe src="my-messages.php">
They want the user to click somewhere, I do not. I want this as an automatic process.
Here's a way to do it, though if the user is doing anything within the iframe they will lose their progress.
window.setInterval(function() {
document.querySelector('iframe.reload').setAttribute('src', 'https://freesecure.timeanddate.com/clock/i5sso5fg/n1328/tluk');
}, 5000);
<iframe class="reload" src="https://freesecure.timeanddate.com/clock/i5sso5fg/n1328/tluk" frameborder="0" width="57" height="18"></iframe>
The simplest way is to use the refresh meta tag. Just add this to the head section of my-messages.php...
<meta http-equiv="refresh" content="5" />
Alternatively, add this to my-messages.php in order to do the same thing with Javscript...
<script>
setTimeout(function() {
window.location.reload();
}, 5000);
</script>
Use javascript to change the src of the iframe to "my-messages.php" again. This is a solution using JQuery to select the element.
<iframe src="my-messages.php" id="frame">
in your JS
var refreshMS = 10000;
var $frame = $('#frame');
var timeoutFunction = function(){
$frame.attr("src", "");
$frame.attr("src", "my-messages.php");
setTimeout(timeoutFunction, refreshMS);
};
setTimeout(timeoutFunction, refreshMS);
This basically sets the src element every 10 seconds, causing the iframe to reload its contents.
Edit: As recommended, non-jquery version
var refreshMS = 10000;
var frame = document.getElementById("frame");
var timeoutFunction = function(){
frame.setAttribute("src", "");
frame.setAttribute("src", "my-messages.php");
setTimeout(timeoutFunction, refreshMS);
};
setTimeout(timeoutFunction, refreshMS);
Related
For example, before redirect, I used
messages.add_message(request, messages.INFO, 'You have successfully updated your listing.')
Then the message will be automatically displayed after redirection, however the message will never disappear, may I know how to hide it after few seconds?
Thanks!!!
You need to write javascript code, use window setTimeout() method to hide message after some time.
// suppose the `id` attribute of element is `message_container`.
var message_ele = document.getElementById("message_container");
setTimeout(function(){
message_ele.style.display = "none";
}, 3000);
// Timeout is 3 sec, you can change it
Put this code inside base.html at the bottom inside <script> tag, so whenever page reloaded after 3
sec it will make your message disappear.
the script:
<script>
setTimeout(function(){
if ($('#msg').length > 0) {
$('#msg').remove();
}
}, 2000) // 2000 millisecond
</script>
the template:
<div id="msg">
{{message}}
</div>
To hide only messages with a certain tag (e.g only INFO messages) you can use the following code inside your HTML document.
<script>
// Get all info messages
var info_messages = document.getElementsByClassName('alert-info');
setTimeout(function(){
for (var i = 0; i < info_messages.length; i ++) {
// Set display attribute as !important, neccessary when using bootstrap
info_messages[i].setAttribute('style', 'display:none !important');
}
}, 3000);
</script>
This one is working fine for me:
var message_ele = document.getElementById("msg");
setTimeout(function() {
message_ele.style.display = "none";
}, 3000);
<span id="msg">
{{messages}}
</span>
Hi I have a array of urls which I want to load in the same browser window one by one. For now I am able to load a single url in a browser window using
window.location = url;
But when I put this window.location in a function and call that function infinitely in a loop with some delay the page just keeps on loading and nothing gets displayed. Code is below:
<html>
<head>
<script>
var urls = ["http://www.howstuffworks.com", "http://example.com"];
var i = 0;
function redirect_url(url)
{
window.location = url;
}
while (true)
{
setTimeout(function() { redirect_url(urls[i]); }, 5000);
// update the index
i = (i + 1) % urls.length;
}
</script>
</head>
What I want is when I open this script file in my browser then the first url's webpage should get loaded and after 5 secs second url's webpage should get loaded and this should continue infinitely.
Here is a method without the While loop; Seems to work well on my end: http://jsfiddle.net/77617znz/2/
var urls = ["http://www.howstuffworks.com", "http://example.com"];
var i = 0;
function redirect_url()
{
if( i <= urls.length )
{
setTimeout(function(){
$('iframe').attr('src', urls[i]);
i++;
redirect_url();
}, 3000);
}
}
redirect_url();
Hope this helps! Let me know if you have any questions.
window.location = url; will load the page with full refresh. Once that happens all the script from the previous page will not be available so what you are trying the achieve will never happen.
May be you can have an iframe on the page and change the iframe source every 5 seconds as you need.
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(function () {
var urls = ["http://www.howstuffworks.com", "http://example.com"];
var i = 0;
function loadIframe(url)
{
$('#iframe').attr('src', url);
}
setInterval(function() {
// update the index
i = (i + 1) % urls.length;
loadIframe(urls[i]);
}, 5000);
loadIframe(urls[i]);
});
</script>
</head>
<body>
<iframe id="iframe" height="100%" width="100%"></iframe>
</body>
</html>
Demo http://plnkr.co/edit/hjx3b234MUDzkSL67RW5?p=preview
I don't think what you're trying to achieve can be done by the code you have posted. If you set the location it will navigate to the new page and your JavaScript will cease to function.
You could try using some other systems such as IFRAMES or ajax requests to load and render them on your page. This will lead to issues where the Origin of your page will not match the one you are loading. This will throw an error and the page will fail to load.
For the IFRAMEs the X-Frame-Options of the page you are loading will prevent it from being displayed. Also if your page is HTTPS and the other page is not it will also fail to load.
Expanding on ShankarSangoli's answers since original code will not work. Looping through and doing the set timeout as 5000 will just load those urls simultaneously 5000 seconds from now. You need to increment that value.
<html>
<head>
<script>
var urls = ["http://www.howstuffworks.com", "http://example.com"];
var timeout = 5000;
function loadIframe(url)
{
$('#iframe').attr('src', url);
}
for (var i = 0; i < urls.length; i++)
{
setTimeout(function() { loadIframe(urls[i]); }, timeout*i);
}
</script>
<iframe id="iframe" height="100%" width="100%"></iframe>
How to determine when document has loaded(or is loading) after loading external css?
Normal page has loaded and complete at first time(with using document.onreadystatechange or document.readyStage), but after time script will call function to place a new stylesheet CSS into HTML for changing a background or images. During change stylesheet, document has still stage complete. Stage never has been changed after calling function? Why?
Timeline(example):
Visit one page : localhost/index.html
Document has stage loading
Document has stage complete
User was trying to change a theme, at this time stage hasnt been changed yet.
UPDATE: Without jQuery:)
UPDATE:
Example problem with using one image:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script>
document.onreadystatechange = function(){
console.log(document.readyState);
};
function checkDocumentState(){
console.log(document.readyState);
return setTimeout(function(){
checkDocumentState();
}, 1000);
}
checkDocumentState();
</script>
</head>
<body>
<img src="" onclick="this.setAttribute('src','http://i.imgur.com/uRBtadp.jpg')" style="width:50px; height:50px; background-color:gray; " /> Press empty image and open new image.
</body>
</html>
FOUND ANSWER: How can I tell when a CSS background image has loaded? Is an event fired?
But hopeless .. lack of universality...
CSS is called after DOM elements are populated. This is why in the days of dial up internet, the page would load all funky looking, and then all of a sudden start to develop into the desired page bit by bit. I would suggest using Jquery instead, where you could use the following code to be able to ensure the document is fully loaded and the CSS is already implemented
$document.ready(function() {
//Insert Code here
}
Hope that helps
Answering the question, how to determine the document has loaded after dynamically loading a css file depends upon the different browser vendors out there. There is not a single sure shot way for all the browsers, but lets tackle the problem one by one for each of these browsers.
Preface
var url = "path_to_some_stylesheet.css",
head = document.getElementsByTagName('head')[0];
link = document.createElement('link');
link.type = "text/css";
link.rel = "stylesheet"
link.href = url;
head.appendChild(link);
Once that appending is done:
Internet Explorer : fires readystatechange and load.
Opera : fires load event via onload.
Chrome : Doesnt fire an event but increments document.styesheets.length only after the file has arrived.
Firefox: I was not able to reliably get anything other than mozAfterPaint.
I wrote this code, what i wanted and worked for me:
window.engineLoading = {images_count:0, images_loaded_count:0, fonts_count:0, fonts_loaded_count:0 };
document.querySelector("a").onclick = function(){ // first elemnet a
var before_stylesheets_length = document.styleSheets.length;
var before_fonts_size = document.fonts.size;
document.fonts.onloadingerror = function(a){
window.engineLoading.fonts_loaded_count++;
}
document.fonts.onloading = function(a){
window.engineLoading.fonts_count++;
}
document.fonts.onloadingdone = function(a){
window.engineLoading.fonts_loaded_count++;
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('link');
style.rel= 'stylesheet';
style.setAttribute("href","./new_style.css");
style.onload = function(){
for(i=before_stylesheets_length; i<document.styleSheets.length; i++){
var rules = document.styleSheets[i].rules;
for(q=0; q<rules.length; q++){
var styles = rules[q].style;
for(s=0; s<styles.length; s++){
console.log(styles[s]);
if((styles[s] == "background-image" || styles[s] == "background") && styles.backgroundImage.length > 0){
window.engineLoading.images_count++;
var body= document.getElementsByTagName('body')[0];
var image = document.createElement('img');
var url = styles.backgroundImage;
url = url.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
image.src = url;
image.width = 0;
image.height = 0;
image.setAttribute("class","pace-load-style");
image.onload = function(e){
console.log(e);
window.engineLoading.images_loaded_count++;
};
image.onerror = function(e){
window.engineLoading.images_laoded_count++;
}
body.appendChild(image);
break;
}
}
}
}
};
style.onerror = function(){};
head.appendChild(style);
setTimeout(function(){
checkCurrentState();
}, 1000);
return false;
};
function checkCurrentState(){
if(window.engineLoading.images_count == window.engineLoading.images_loaded_count && window.engineLoading.fonts_count == window.engineLoading.fonts_loaded_count){
console.log("loaded"); return true;
}console.log("still loading...");
return setTimeout(function(){
checkCurrentState();
}, 1000);
};
UPDATE: Scipt has bug on localfile because of empty rule. CSSRules is empty I don't worry about it , and no need fix it.
UPDATE: Mozilla Firefox hasnt reference document.fonts.
I would like to load a bunch of iframes at different times, not all at the same time but one after another like one at 300000ms, then 209000ms, then 257000ms, etc. They will all need to be loaded at different times after each other and I need to be able to change them later if needed. I would like it to be when I click a button not as an onload event. I have little experience in javascript.
Please no jQuery.
Thanks!
Edit: I want the iframes to load on top of one another, or replace one another, not load a bunch of them in a list. I will only be putting up around 5 iframes total. Sorry for not being specific enough. Something like this, except for the time working:
<a target='page' href='http://framedsite1'>#1 (visible for 300000ms)</a>
<a target='page' href='http://framedsite2'>#2 (visible for 209000ms)</a>
<a target='page' href='http://framedsite3'>#3 (visible for 257000ms)</a>
<iframe id='page' name='page' src=''></iframe>
Except for auto playing through them all, not as a bunch of links but by being clicked on and loaded into the iframe after a set amount of time after the previous frames time has gone by, kind of like a playlist. They will all need to be displayed for different amounts of time then load the next iframe, I am emphasizing that they all will be different amounts of time.
You can use setInterval() and loop through to set the source for each iframe:
var iframes = document.getElementsByTagName("iframe"); //retrieves a NodeList of iframes
var i = 0;
var interval = window.setInterval(function(){
if(i < iframes.length){
iframes[i].src = "//example.com"; //source of the iframes
i++;
}else{
window.clearInterval(interval);
}
}, 3000); //interval to load each iframe in milliseconds
Demo
If you want to trigger it with a button click, just wrap it in a function and attach an event listener:
document.getElementById("idOfButton").addEventListener("click", function(){
var iframes = document.getElementsByTagName("iframe"); //retrieves a NodeList of iframes
var i = 0;
var interval = window.setInterval(function(){
if(i < iframes.length){
iframes[i].src = "//example.com"; //source of the iframes
i++;
}else{
window.clearInterval(interval);
}, 3000); //interval to load each iframe in milliseconds
});
Demo
<html>
<head>
<script>
var iframes;
var loadIframes = function(){
iframes = document.getElementsByClassName('custom-iframe');
for(var i=0; i<iframes.length; i++){
var iframe = iframes[i],
seconds = iframe.getAttribute('data-seconds'),
src = iframe.getAttribute('data-src');
run(i, src, seconds);
}
}
var run = function(i, src, seconds){
setTimeout(function(){
iframes[i].src = src;
}, seconds);
}
</script>
</head>
<body>
<button onclick="loadIframes()">Load iframes</button>
<iframe class="custom-iframe" data-seconds="3000" data-src="http://example.com"></iframe>
<iframe class="custom-iframe" data-seconds="900" data-src="http://google.com"></iframe>
</body>
</html>
Just change "data-seconds" and "data-src" attributes in each iframe, and put "custom-frame" class in the iframe elements.
When you click the button, they will run based on the iframe custom configs.
<html>
<head>
<script>
var buttons = document.getElementsByClassName('iframe-button');
var iframe = document.getElementById('my-iframe');
for(var i=0; i < buttons.length; i++){
var button = buttons[i];
button.addEventListener("click", function(){
var src = button.getAttribute('data-src');
iframe.src = src;
});
}
</script>
</head>
<body>
Example.com
Google.com
<iframe id="my-iframe"></iframe>
</body>
Just need to repeat those <a> elements. Put "iframe-button" class on them, and "data-src" attribute if the URL value.
I have an iframe in my site that must reload every second (it's just reloading simple HTML for data analysis). This causes a really annoying white flash each time it reloads.
I have put hours of research into trying to remove this flash. Here's what I have (which doesn't work), which creates a new iframe, adds it to the DOM, and then removes the old one, effectively reloading the page. It still flashes white though:
$( document ).ready(function() {
setInterval(function() {
var container = document.getElementById('bottom-frame-container');
var source = container.getElementsByTagName('iframe')[0];
var newFrame = document.createElement('iframe');
for (i = 0; i < source.attributes.length; i++) {
var attr = source.attributes[i];
newFrame.setAttribute(attr.name, attr.value);
}
newFrame.style.visibility = 'hidden';
newFrame.id = 'bottom-frame';
container.appendChild(newFrame);
newFrame.style.visibility = 'visible';
container.removeChild(container.getElementsByTagName('iframe')[0]);
}, 1000);
});
The iframe code is simply:
<div id="bottom-frame-container">
<iframe id="bottom-frame" width="100%" height="60%" frameborder="0" allowTransparency="true" src="http://10.62.0.15/haproxy?stats">
</div>
I'm completely open to any suggestions or alternative approaches here, I'm getting a bit desperate!
Here's how i would handle this issue : have one 'load' div on top of the iframe to prevent the blinking from being seen.
Then before loading you fadein the warning --> when fadein is finished you trigger load --> when load is finished you fadeout the warning.
fiddle is here :
http://jsfiddle.net/bZgFL/2/
html is :
<iframe
width=500px
height=300px
id = 'myFrame'
style='position:absolute;top:0;'
src = 'http://jsfiddle.net/'
>
</iframe>
<div id = 'myLoad'
style='float:top;top:0;
position:absolute;
background-color:#CCC;
min-width:500px;
min-height:300px;
'>
<div style='position:absolute;top:130px;left:200px;'>
<b> Loading... </b>
</div>
</div>
</div>
code is (using jQuery)
var ifr = document.getElementById('myFrame');
setFrame();
setInterval(setFrame, 3000);
function setFrame() {
$('#myLoad').fadeIn(200, setAdress);
}
function setAdress() {
ifr.onload=function() { $('#myLoad').fadeOut(200) ;}
ifr.src = 'http://jsfiddle.net/';
}
Obviously it needs fine tuning for the look, and if you want the user to be able to click the iframe, you'll have to disable pointer on top div, but it should get you going.
Can you put the two iFrames on the page and hide show them with CSS. This much less of an impact on the page than removing and inserting elements into the DOM.
Then add an onload event to both of them that triggers the current iFrame to hide and reload, while the new on shows? Use RequestAninationFrame to help reduce flicker. Code would look something like this.
var currentIFrame = 1;
$('iframe').on('load',function(){
$(this).show()
$('#iframe'+(currentIFrame=1-currentIFrame)).hide().delay(1000).reload();
})
This way you only do the switch once your sure the content has fully loaded.
I know this is an old question but I'm really not sure why someone didn't post this obvious solution....
Just paste this javascript code into any page that has an iframe.
<script>
// Preventing whiteflash in loading iframes.
(function () {
var div = document.createElement('div'),
ref = document.getElementsByTagName('base')[0] ||
document.getElementsByTagName('script')[0];
div.innerHTML = '<style> iframe { visibility: hidden; } </style>';
ref.parentNode.insertBefore(div, ref);
window.onload = function() {
div.parentNode.removeChild(div);
}
})();
</script>
It will simply renfer any iframe visibility:hidden until which time the iframe is loaded and then make it visible.