Delaying display of the new content until layout is complete - javascript

When dynamically changing content within a div is there a way of delaying the display of the new content until all layout is complete?
I am using javascript and ajax to update the contents of a div and when I insert the html returned by the ajax script it appears to doing the layout of the new content after the elements are visible, spilling outside of the target div
While this happens quickly and the end result is exactly as I desire it to be it does create an unpleasant 'flickering' that I would like to avoid
javascript
$requestURL = 'Scripts/getCategoryItems.php?Category='+$category+'&PageLength='+$pageLength+'&Page='+$page ;
AjaxRequest.open('GET',$requestURL,true);
AjaxRequest.onreadystatechange = function()
{ if(AjaxRequest.readyState == 4)
{
if (AjaxRequest.responseText !== 'false')
{ TargetContainer.style.display = "none";
TargetContainer.innerHTML=AjaxRequest.responseText;
TargetContainer.style.display = "block";
} else { alert(AjaxRequest.responseText); } ;
document.body.className = '';
}
};
document.body.className = 'waiting';
AjaxRequest.send();
Html:
<div id="Content" style="float:left; width:820px; height:550px; max-height:550px; color:#E0E0E0; padding-top:30px; overflow:hidden;"></div>

You could run your code within the document ready so that the document is fully loaded before you start making your ajax call.
EDIT: Or if you're not using jQuery then the window.onload event.

Related

Onload need to work only once

Good day everyone i'm having a trouble about working my onload only once . because when i refreshes the page or if i am going to another page it always load.
here is my code so far:
JS
<!--Auto load the on overlay function-->
<script>
window.onload = function openNav() {
document.getElementById("myNav").style.width = "100%";
splashScreen();
}
function closeNav() {
document.getElementById("myNav").style.width = "0%";
}
</script>
and here's my js functionality for my splashscreen.js
//use onload when in your html the context is not inside
//the <header>
//create a splashScreen function
function splashScreen(){
//get the element on the html side with the id of "skip"
var skipButton = document.getElementById("skip");
//counter for the countdown
var counter = 5;
//create an element <p>
var newElement = document.createElement("p");
newElement.innerHTML = "Skip this 5 seconds";
var id;
skipButton.parentNode.replaceChild(newElement, skipButton);
id = setInterval(function(){
counter--;
if(counter < 0){
//replace the newElement on else condition statement
newElement.parentNode.replaceChild(skipButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = "You can skip this in " + counter.toString() + " seconds.";
}
}, 1000);
}
and this is how i call it on my html
<html>
<body>
<!--SplashScreen JS-->
<script src="<?php echo base_url('assets/public/js/splashscreen.js');?>">
</script>
When you refresh the page or go to another page, then back to your original page, the page is reloading, thus the onLoad handler is being called.
If you want certain functionality to only happen once, then one thing you can try is setting a cookie that you can check on page load. If the cookie is set, you know you already loaded it once, and don't run the code again. If not, you run the code, then set the cookie.
Useful link for cookies:
https://www.w3schools.com/js/js_cookies.asp
To be able to know that the splash screen has already been displayed for a given user, you need to store something to that effect that persists between page load events. Since the page will reload when the refresh button is clicked or when coming back to the page after being there earlier, this stored item can't be in the page itself, because it will just get reinitialized every time the page loads.
Cookies (as mentioned in another answer) are an option, but localStorage, I think is much simpler. It works like this:
// Once the window is loaded...
window.addEventListener("load", function(){
// Check localStorage to see if the splash screen
// has NOT already been displayed
if(!localStorage.getItem("splash")){
// Splash has not been displayed, so show it:
splashScreen();
// Store a value in localStorage to denote that the splash screen
// has now been displayed
localStorage.setItem("splash", "true");
}
});
One approach is to set .name property of window, which remains set after window.
const NAME = "once";
window.onload = function openNav() {
document.getElementById("myNav").style.width = "100%";
if (this.name !== NAME) {
this.name = NAME;
splashScreen();
} else {
// do other stuff
console.log(this.name)
}
}

Click on link to navigate another page without header, footer change

my website has fixed header and footer components. I have a link on body page. when i click on link, it should navigate to another page without changing header and footer component. any one have idea about how to achieve it using jquery/javascript.
You can use a XMLHttpRequest directly to your desired html page, like this:
function load_htm()
{
var xml = new XMLHttpRequest();
//here your content to be loaded
var elem = document.getElementById('content');
//here goes your target html file...
url = "/yourfile.htm";
//this is not the better way to, but will clear the element...
elem.innerHTML = '';
if (xml !== null) {
xml.open('GET', url, true);
xml.send();
xml.onreadystatechange = function() {
if (xml.readyState === 4) {
//getting the results and assign to element
response = xml.responseText;
elem.innerHTML = response;
}
}
}
}
html:
<div id="footer"></div>
<div id="link" onclick="load_htm();"></div>
<div id="content"></div>
<div id="header"></div>

reload div javascript only ajax needed?

please refer to JSFiddle link: https://jsfiddle.net/s11oo2gg/.
We are not allowed to use jQuery and iframe here.
The problem right now if you click on resistor first and hover over different content images then come back out by clicking the X mark, the content image would get stucked where you left off and would not load the the other content images properly. It would show a broken image link.
I like to reload only the <div id="slider1_contain"> everytime I click on <span class="closeButton">(X mark) so the target content images can be loaded accordingly.
I dont not want to have location.reload(); to resolve this when the X is click. I dont want to reload the whole page but only the div.
I saw people were asking the same question and solve it with AJAX. Do I need AJAX for this case? Or is there something we can do in the following javascript?
Thank you in advance!!
<script type="text/javascript">
function showContent(target){
document.getElementById(target).style.display = 'block';
document.getElementById("boxThumb").style.display = 'none';
}
function hideContent(target){
document.getElementById(target).style.display = 'none';
document.getElementById("boxThumb").style.display = 'block'
}
</script>
<script type="text/javascript">
var children = document.querySelectorAll('.toggle > section[id]');
function showDetailContent(target) {
// Simply loop over our children and ensure they are hidden:
for (var i = 0, child; child = children[i]; i++) {
child.style.display = 'none';
}
// Now, show our child we want to show
document.getElementById(target).style.display = 'block';
}
</script>
If you want to reload just the div, you can use innerHTML.
document.getElementById(target).innerHTML = '<img src="image.jpg">';

Refresh iframe content without white flash

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.

How to prevent iframe load event?

I have an iframe and couple of tables on my aspx page. Now when the page loads these tables are hidden. The iframe is used to upload file to database. Depending on the result of the event I have to show a particular table on my main page (these tables basically have "Retry","next" buttons...depending on whether or not the file is uploaded I have to show respective button).
Now I have a JavaScript on the "onload" event of the iframe where I am hiding these tables to start with. When the control comes back after the event I show a particular table. But then the iframe loads again and the tables are hidden. Can any one help me with this problem. I don't want the iframe to load the second time.
Thanks
mmm you said you're on aspx page,
I suppose that the iframe do a postback, so for this it reload the page.
If you can't avoid the postback, you've to set a flag on the main page just before posting back, and check against that while you're loading...
...something like:
mainpage.waitTillPostBack = true
YourFunctionCausingPostBack();
..
onload=function(){
if(!mainpage.waitTillPostBack){
hideTables();
}
mainpage.waitTillPostBack = false;
}
I am not sure what your problem is, but perhaps your approach should be a little different. Try putting code into the iframe what would call functions of the parent. These functions would display the proper table:
<!-- in the main page --->
function showTable1() {}
<!-- in the iframe -->
window.onload = function () {
parent.showTable1();
}
This would put a lot of control into your iframe, away from the main page.
I don't have enough specifics from your question to determine if the iframe second load can be prevented. But I would suggest using a javascript variable to check if the iframe is being loaded a second time and in that case skip the logic for hiding the tables,
This is my code
function initUpload()
{
//alert("IFrame loads");
_divFrame = document.getElementById('divFrame');
_divUploadMessage = document.getElementById('divUploadMessage');
_divUploadProgress = document.getElementById('divUploadProgress');
_ifrFile = document.getElementById('ifrFile');
_tbRetry = document.getElementById('tbRetry');
_tbNext=document.getElementById('tblNext');
_tbRetry.style.display='none';
_tbNext.style.display='none';
var btnUpload = _ifrFile.contentWindow.document.getElementById('btnUpload');
btnUpload.onclick = function(event)
{
var myFile = _ifrFile.contentWindow.document.getElementById('myFile');
//Baisic validation
_divUploadMessage.style.display = 'none';
if (myFile.value.length == 0)
{
_divUploadMessage.innerHTML = '<span style=\"color:#ff0000\">Please select a file.</span>';
_divUploadMessage.style.display = '';
myFile.focus();
return;
}
var regExp = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.doc|.txt|.xls|.docx |.xlsx)$/;
if (!regExp.test(myFile.value)) //Somehow the expression does not work in Opera
{
_divUploadMessage.innerHTML = '<span style=\"color:#ff0000\">Invalid file type. Only supports doc, txt, xls.</span>';
_divUploadMessage.style.display = '';
myFile.focus();
return;
}
_ifrFile.contentWindow.document.getElementById('Upload').submit();
_divFrame.style.display = 'none';
}
}
function UploadComplete(message, isError)
{
alert(message);
//alert(isError);
clearUploadProgress();
if (_UploadProgressTimer)
{
clearTimeout(_UploadProgressTimer);
}
_divUploadProgress.style.display = 'none';
_divUploadMessage.style.display = 'none';
_divFrame.style.display = 'none';
_tbNext.style.display='';
if (message.length)
{
var color = (isError) ? '#008000' : '#ff0000';
_divUploadMessage.innerHTML = '<span style=\"color:' + color + '\;font-weight:bold">' + message + '</span>';
_divUploadMessage.style.display = '';
_tbNext.style.display='';
_tbRetry.style.display='none';
}
}
tblRetry and tblNext are the tables that I want to display depending on the result of the event.

Categories

Resources