my goal is to display a loading curtain when a query to Quick-Base takes too long.
I have the following code that I thought it was going to work but it somehow does not. Everything works except for the loading curtain because it is never executed when it should be.
My code:
<script>
window.onload = function(){
// .. more code here not related ...
function selectedValueChanged() {
$('#curtain').show();
var e = document.getElementById("record_id_select");
var value_selected = e.value;
var CO_picked_record_id = parseInt(value_selected);
var query_CO_line_details = "{'"+related_CO_fid+"'.EX.'"+CO_picked_record_id+"'}";
var records = getRecords(table_CO_line_details_DBID,query_CO_line_details);
var data_array = createArrayFromRecordsDrilled(records,CO_detail_record_categories);
var table_div = tableCreate(data_array,'table_container_1',"Please Enter Quantities",headerList);
$('#table_container_1').replaceWith(table_div);
$('#curtain').hide();
}
}
</script>
<div id='curtain' style='position:absolute;top:0;left:0;margin:0;background:rgba(255,255,255,.3); display:none; width:100%;height:100%;'><img id ="loading_text" src="loader.gif"></div>
</body>
The code works but the curtain is never shown even if the query takes a couple of seconds (as much as 6 seconds). If I comment out the line "$('#curtain').hide();" I can see the loading curtain working as expected but only after the query has finished. It is as if the function is not been executed line by line but it waits first to complete the query and then to show the curtain. I'm sure I'm missing something but I don't know what. Thank you.
use this instead(no need to add any HTML to page) :
function showLoading() {
if (document.getElementById("loadingDiv"))
return;
var div = document.createElement("div");
var img = document.createElement("img");
var span = document.createElement("span");
span.appendChild(document.createTextNode("Loading ..."));
span.style.cssText = "margin-top:50vh;font-family:IranSans;direction:rtl;color:#f78d24;"
img.src = "/images/LoadingImage.png";
img.style.cssText = "display:block;margin:auto;margin-top:calc(50vh - 64px);width:128px;height:128px;"
div.style.cssText = "position:fixed;width:100vw;height:100vh;background-color:rgba(0,0,0,0.85);top:0px;left:0px;z-index:10000;text-align:center";
div.id = "loadingDiv";
div.appendChild(img);
div.appendChild(span);
document.body.appendChild(div);
}
function hideLoading() {
var div = getElementById("loadingDiv");
if (div)
document.body.removeChild(div);
}
The solution as #keith suggested was to "transform" the getRecords function from synchronous to asynchronous.
I ended up making the whole function selectedValueChanged() "asynchronous" by using the setTimeout trick.
One solution that worked for me was the following:
function selectedValueChanged() {
var e = document.getElementById("record_id_select");
var value_selected = e.value;
var CO_picked_record_id = parseInt(value_selected);
var query_CO_line_details = "{'"+related_CO_fid+"'.EX.'"+CO_picked_record_id+"'}";
var records = getRecords(table_CO_line_details_DBID,query_CO_line_details);
var data_array = createArrayFromRecordsDrilled(records,CO_detail_record_categories);
var table_div = tableCreate(data_array,'table_container_1',"Please Enter Quantities",headerList);
$('#table_container_1').replaceWith(table_div);
}
}
function loadingSelectedValueChanged(callbackFunct){
setTimeout(function(){
callbackFunct()
$('#curtain').hide();
},10);
}
function selectedValueChangedUP() {
$('#curtain').show();
loadingSelectedValueChanged(selectedValueChanged);
}
And now instead of calling selectedValueChanged, I call selectedValueChangedUP.
What SetTimeout does is to execute the function that receives as parameter after a given amount of time. This process is done in an "asynchronous" way.
Related
In addition to this topic execute a javascript after page load is complete I noticed the solution didn't work for loading a map. I do have a similar use case. However, if I follow the script the script needed doesn't load.
I want to load a map after the loading of the page is finished, however I do see the script in the page source, but no script is executed.
The source is:
var mst_width = "96%";
var mst_height = "350vh";
var mst_border = "0";
var mst_map_style = "simple";
var mst_mmsi = "244770624";
var mst_show_track = "true";
var mst_show_info = "true";
var mst_fleet = "";
var mst_lat = "";
var mst_lng = "";
var mst_zoom = "";
var mst_show_names = "0";
var mst_scroll_wheel = "true";
var mst_show_menu = "true";
window.onload = function () {
var element = document.createElement("script");
element.src = "http://www.myshiptracking.com/js/widgetApi.js";
document.getElementsByTagName("head")[0].appendChild(element);
}
In the page source I see:
var mst_width = "96%";
var mst_height = "350vh";
var mst_border = "0";
var mst_map_style = "simple";
var mst_mmsi = "244770624";
var mst_show_track = "true";
var mst_show_info = "true";
var mst_fleet = "";
var mst_lat = "";
var mst_lng = "";
var mst_zoom = "";
var mst_show_names = "0";
var mst_scroll_wheel = "true";
var mst_show_menu = "true";
window.onload = function () {
var element = document.createElement("script");
element.src = "http://www.myshiptracking.com/js/widgetApi.js";
document.getElementsByTagName("head")[0].appendChild(element);
}
Can someone please point me in the direction on how to get the script executed? I also assumed that the script should be appended to the 'body' instead of the 'head'm but I'm not sure about it.
Thanks!
Edit based change of head to body:
<script>
var mst_width="96%";var mst_height="350vh";var mst_border="0";var mst_map_style="simple";var mst_mmsi="244770624";var mst_show_track="true";var mst_show_info="true";var mst_fleet="";var mst_lat="";var mst_lng="";var mst_zoom="";var mst_show_names="0";var mst_scroll_wheel="true";var mst_show_menu="true";
window.onload = function() {
var element = document.createElement("script");
element.src = "http://www.myshiptracking.com/js/widgetApi.js";
document.getElementsByTagName("body")[0].appendChild(element );
}
</script>
So, finally I managed to solve the problem and got the desired map in my browser... using the following HTML+JS code (which you can run with the button below):
<html lang="en-US" prefix="og: http://ogp.me/ns#">
<head>
<script>
var mst_width="100%";var mst_height="450px";var mst_border="0";var mst_map_style="terrain";var mst_mmsi="";var mst_show_track="";var mst_show_info="";var mst_fleet="";var mst_lat="";var mst_lng="";var mst_zoom="";var mst_show_names="0";var mst_scroll_wheel="true";var mst_show_menu="true";
function loadMap() {
var element = document.createElement("script");
element.setAttribute("id", "myshiptrackingscript");
element.setAttribute("async", "");
element.setAttribute("defer", "");
element.src = "http://www.myshiptracking.com/js/widgetApi.js";
document.getElementById("mapContent").appendChild(element );
}
window.onload = loadMap
console.log('Registered onload')
</script>
</head><body>
<div id="mapContent" />
</body></html>
Two points of attention:
you should add the created script tag as child of a tag belonging to the body ot the page (I used <div id="mapContent"/> and getElementById to access it)
you should load the HTML page through a http:// URL, not through a a file:// one: with the latter you get an error with message like "Browser does not support embedded objects"
I hope this can help you to solve the problem in you real case!
There are many ways to invoke your function when the page has loaded.
My vanilla's js tool of choice most of the time is:
window.addEventListener('DOMContentLoaded', function(){
//your bindings and functions
}
That way of proceeding is preferred to your onload method as otherwise, you won't be able to attach multiple events when the DOM loads completely.
Try this:
window.onload=function(){
document.write('<script src="http://www.myshiptracking.com/js/widgetApi.js>
</script>');
}
wrap your javascript code with this:
if(document.readyState === 'complete') {
// good to go! Put your code here.}
I have an incomplete script here that just needs to give a few adjustments of positions and add the exchange of images with the function Onclick of JavaScript but do not remember how to do more this exchange I would like to know what the error of the following code and how to fix, since I thank you.
// Like Normal e like Marcado
var imgLike01 = "images/mylike.png"
var imgLike02 = "images/like.png"
// Deslike Normal e deslike desmarcado
var imgDeslike01 = "images/mydeslike.png"
var imgDeslike02 = "images/deslike.png"
var likebtn = document.getElementById("likebtn");
var deslikebtn = document.getElementById("deslikebtn");
function like () {
likbtn.img.src = imgLike02;
}
function deslike () {
deslikebtn.img.src = imgDeslike02;
}
function Trade(){
if ($like).click(function() {
likbtn.img.src = imgLike01;
});
if ($deslike).click(function() {
deslikebtn.img.src = imgDeslike01;
});
}
Note This is the exchange of images from an old like system in JavaScript, a sum script and only missing image switching.
Add an eventListener to likebtn:
likebtn.addEventListener("click", like);
Do the same for deslikebtn.
var malediv = document.querySelector('.male');
var femalediv = document.querySelector('.female');
var male_sources = [
"/images/m1.png",
"/images/m2.png",
"/images/m3.png",
"/images/m4.png",
"/images/m5.png",
"/images/m6.png",
"/images/m7.png",
"/images/m8.png",
]
var female_sources = [
"/images/f1.png",
"/images/f2.png",
"/images/f3.png",
"/images/f4.png",
"/images/f5.png",
"/images/f6.png",
"/images/f7.png",
"/images/f8.png",
]
function displayRandMaleImage() {
malediv.innerHTML = "";
var malerandom_number = Math.floor(Math.random() *
male_sources.length);
var random_male_image_source = male_sources[malerandom_number];
maleimg = document.createElement('img');
maleimg.setAttribute('src', random_male_image_source);
malediv.append(maleimg);
alert('maleimagedisplayed');
}
function displayRandFemaleImage() {
femalediv.innerHTML = "";
var femrandom_number = Math.floor(Math.random() * female_sources.length);
var random_female_image_source = female_sources[femrandom_number];
femaleimg = document.createElement('img');
femaleimg.setAttribute('src', random_female_image_source);
div.append(femaleimg);
}
function displayRandImages(){
displayRandMaleImage();
displayRandFemaleImage();
alert('SKEEET');
}
none of my display random image fundtions are working in my html page that this is embedded in. I even added a test function "anAlert" that works perfectly. Please help me to understand what i can do to make this work.
There are two reasons why it isn't working.
1) You haven't defined the button. Which should've been done like:
var button = document.querySelector('.button_class');
or using the id:
var button = document.getElementById('button_id');
2) Your function to call the other two display functions is named displayRandImages()
function displayRandImages(){
displayRandMaleImage();
displayRandFemaleImage();
alert('SKEEET');
}
whereas, you've used the function displayRandomImage() in your click event:
button.addEventListener('click', displayRandomImage);
displayRandImages() != displayRandomImage()
button is not defined
button.addEventListener('click', displayRandomImage);
You should use it like
document.getElementById('buttonid').addEventListener('click', displayRandImages);
where 'buttonid' is id of your button, should be defined in html.
One more thing, as you are accessing button outside any other js function, So it'll be called on page load.
So you have to write this javascript after your html code so that it'll be called after button element rendered in HTML.
I am a beginner of javascript and jquery and i have 11 image tags in html. I want to
basically change sources of these tags using js and jquery. This code is not working and I am not getting any errors in firebug, can some one please tell me where I am doing wrong?
var imagesArray2=["01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png","10.png","11.png"];
var elementArray2 = ["#img1","#img2","#img3","#img4","#img5","#img6","#img7","#img8","#img9","#img10","#img11"];
var imagesArray,elementArray;
var elementInArray;
document ready
$(function(){
setInterval(Myfunction(),1000);});
my function code which has a loop based on elementsInArray variable value and it calls imageFadeAnimations function
function Myfunction(){
if(elementsInArray === 0){
imagesArray = imagesArray2;
elementArray = elementArray2;
elementsInArray = elementArray.length;
var imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
else
{
elementsInArray=elementArray.length;
imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
}
takes an integer as argument
function imageFadeAnimations(imageChanges){
for(var k = 0;k<imageChanges;k++){
var element = Math.floor(Math.random()*elementsinArray);
var image=Math.floor(Math.random()*elementsinArray);
imageChanger(elementArray[element],imageArray[image]);
elementArray.splice(element,1);
imagesArray.splice(image,1);
}
}
function imageChanger(b1,b2){
$(b1).fadeOut(500,function(){
$(b1).attr("src",b2);
$(b1).fadeIn(500);
});
}
You are making heavy weather out of something that jQuery can make very simple.
First wrap your images in an element (typically a div or a span) with id="imageContainer".
Now, if I understand correctly, your code will simplify to :
$(function() {
var imagesArray = ["01.png", "02.png", "03.png", "04.png", "05.png", "06.png", "07.png", "08.png", "09.png", "10.png", "11.png"],
$images = $("img", "#imageContainer");
setInterval(function() {
$images.each(function() {
var $img = $(this),
i = Math.min(imagesArray.length-1, Math.floor(Math.random() * imagesArray.length));
$img.fadeOut().promise().then(function() {
$img.attr("src", imagesArray[i]).fadeIn(500);
});
});
}, 1000);
});
EDIT 1
As #mplungjan points out below ...
If the img nodes were initialised with src attributes, then imagesArray can be composed by grabbing the srcs from the DOM as follows (replacing two lines above) :
var $images = $("img", "#imageContainer"),
imagesArray = $images.map(function() { return this.src; }).get();
I believe this jquery/zepto code is not the smaller, but the easier to understand:
function changeImg(){
$("#img1").attr('src', '01.png');
$("#img2").attr('src', '02.png');
$("#img3").attr('src', '03.png');
$("#img4").attr('src', '04.png');
$("#img5").attr('src', '05.png');
$("#img6").attr('src', '06.png');
};
http://www.ultralocal.fr/refonte/test.php
As you can see, I have a menu with a few links. All of them, except one, launch a small script that changes the background color according to the onclick thing. The "Talweg" link work another way, it launches a bigger script that actually makes the background color change from time to time, progressively.
What I would like to know is how I can make the other links stop the Talweg script and just change the bgcolor for once.
the menu:
× Désœuvrements<br />
× Recettes<br />
× Talweg<br />
the simple script:
function changeBGC(color){
document.bgColor = color;
}
the bigger script that can be launched when one clicks on Talweg but I want to stop when one clicks on the other links.
// Set 1 dark to medium
// Set 2 light to medium
// Set 3 very dark to very light light
// Set 4 light to very light
// Set 5 dark to very dark
var fade_effect=4
// What type of gradient should be applied Internet Explorer 5x or higher?
// Set "none" or "horizontal" or "vertical"
var gradient_effect="none"
var speed=800
var browserinfos=navigator.userAgent
var ie4=document.all&&!document.getElementById
var ie5=document.all&&document.getElementById&&!browserinfos.match(/Opera/)
var ns4=document.layers
var ns6=document.getElementById&&!document.all
var opera=browserinfos.match(/Opera/)
var browserok=ie4||ie5||ns4||ns6||opera
if (fade_effect==1) {
var darkmax=1
var lightmax=127
}
if (fade_effect==2) {
var darkmax=180
var lightmax=254
}
if (fade_effect==3) {
var darkmax=1
var lightmax=254
}
if (fade_effect==4) {
var darkmax=204
var lightmax=254
}
if (fade_effect==5) {
var darkmax=1
var lightmax=80
}
var hexc = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F')
var newred
var newgreen
var newblue
var oldred
var oldgreen
var oldblue
var redcol_1
var redcol_2
var greencol_1
var greencol_2
var bluecol_1
var bluecol_2
var oldcolor
var newcolor
var firsttime=true
var stepred=1
var stepgreen=1
var stepblue=1
function setrandomcolor() {
var range=(lightmax-darkmax)
if (firsttime) {
newred=Math.ceil(range*Math.random())+darkmax
newgreen=Math.ceil(range*Math.random())+darkmax
newblue=Math.ceil(range*Math.random())+darkmax
firsttime=false
}
oldred=Math.ceil(range*Math.random())+darkmax
oldgreen=Math.ceil(range*Math.random())+darkmax
oldblue=Math.ceil(range*Math.random())+darkmax
stepred=newred-oldred
if (oldred>newred) {stepred=1}
else if (oldred<newred) {stepred=-1}
else {stepred=0}
stepgreen=newgreen-oldgreen
if (oldgreen>newgreen) {stepgreen=1}
else if (oldgreen<newgreen) {stepgreen=-1}
else {stepgreen=0}
stepblue=newblue-oldblue
if (oldblue>newblue) {stepblue=1}
else if (oldblue<newblue) {stepblue=-1}
else {stepblue=0}
fadebg()
}
function fadebg() {
if (newred==oldred) {stepred=0}
if (newgreen==oldgreen) {stepgreen=0}
if (newblue==oldblue) {stepblue=0}
newred+=stepred
newgreen+=stepgreen
newblue+=stepblue
if (stepred!=0 || stepgreen!=0 || stepblue!=0) {
redcol_1 = hexc[Math.floor(newred/16)];
redcol_2 = hexc[newred%16];
greencol_1 = hexc[Math.floor(newgreen/16)];
greencol_2 = hexc[newgreen%16];
bluecol_1 = hexc[Math.floor(newblue/16)];
bluecol_2 = hexc[newblue%16];
newcolor="#"+redcol_1+redcol_2+greencol_1+greencol_2+bluecol_1+bluecol_2
if (ie5 && gradient_effect!="none") {
if (gradient_effect=="horizontal") {gradient_effect=1}
if (gradient_effect=="vertical") {gradient_effect=0}
greencol_1 = hexc[Math.floor(newred/16)];
greencol_2 = hexc[newred%16];
bluecol_1 = hexc[Math.floor(newgreen/16)];
bluecol_2 = hexc[newgreen%16];
redcol_1 = hexc[Math.floor(newblue/16)];
redcol_2 = hexc[newblue%16];
var newcolorCompl="#"+redcol_1+redcol_2+greencol_1+greencol_2+bluecol_1+bluecol_2
document.body.style.filter=
"progid:DXImageTransform.Microsoft.Gradient(startColorstr="+newcolorCompl+", endColorstr="+newcolor+" GradientType="+gradient_effect+")"
}
else {
document.bgColor=newcolor
}
var timer=setTimeout("fadebg()",speed);
}
else {
clearTimeout(timer)
newred=oldred
newgreen=oldgreen
newblue=oldblue
oldcolor=newcolor
setrandomcolor()
}
}
Thanks
The longer-running script keeps re-executing itself with selfTimeout. If you want to stop it, all you need to do is call clearTimeout on the returned variable:
clearTimeout(timer)
Of course, you may need to be a bit more careful, because the script may be in the middle of the execution when you clear the timeout. One way to deal with it would be to set a flag indicating that the script need not be re-executed again. You can pull variable declarations out of the functions to make the code easier to read. So your code can look like this:
//variable declaration for use in fadebg function
var timer;
//variable declaration for the flag
var contBg = true;
//stop your previous script
function stopRandomBg() {
clearTimeout(timer);
contBg = false;
}
//changes to fadebg function
function fadebg() {
...
//change this line
//var timer=setTimeout("fadebg()",speed);
//to
if(contBg) {
timer=setTimeout("fadebg()",speed);
}
...
}
These additional changes will take care of the case when the script is in the middle of execution when you try to stop it - it will complete the execution pass and then stop.
Now all you need to do is to add onClick event listener to your link to call stopRandomBg function.
You have to make the timer variable global instead of local.
var timer;
then clear the timer when ever you call other links.
function changeBGC(color){
clearTimeout(timer);
document.bgColor = color;
}