Javascript loading bar - javascript

how would I make a loading bar, I would also like it to be "stackable" like have 2 on the same page and have the first one trigger the second one when its complete then the second one redirects to a URL at 100%, this may or may not be basic to you guys but its really hard for me. I have an outdated JavaScript one already but it disappears when I add the second one and don't know how to make it trigger the second one. if you want to try and edit the one I have so It triggers the second one and is stackable then just say so, but note its outdated, I know that, I am using it because it is really simple to configure and setup.
This is the relevant code so far:
var currentAdb = 0;
var imgCtb = 25;
function cycleb() {
var output = '[';
for (var i = 0; i < imgCtb; i++) {
output += i > currentAdb ? ' ' : '/';
}
output += ']';
document.getElementById('adLinkb').innerHTML = output;
++currentAdb;
if(currentAdb == imgCtb) {
window.clearInterval(myInterval);
}
}
var myInterval = window.setInterval(cycleb, 500);
#adLinkb {
font-size: 12px;
color: #000;
font-family: monospace;
}
<div id="adLinkb"></div>

OK, let's expand the code I gave you in the last question by grouping it into functions and introducing callbacks:
function buildBar(id, callback) {
var currentAdb = 0;
var imgCtb = 25;
function cycleb() {
var output = '[';
for (var i = 0; i < imgCtb; i++) {
output += i > currentAdb ? ' ' : '/';
}
output += ']';
document.getElementById(id).innerHTML = output;
++currentAdb;
if (currentAdb == imgCtb) {
window.clearInterval(myInterval);
if (typeof callback == 'function') {
callback();
}
}
}
var myInterval = window.setInterval(cycleb, 500);
}
function callback1() {
buildBar('adLinkb2', callback2);
}
function callback2() {
//window.location... stuff here
alert('redirect should go here');
}
buildBar('adLinkb', callback1);
#adLinkb,
#adLinkb2 {
font-size: 12px;
color: #000;
font-family: monospace;
}
<div id="adLinkb"></div>
<div id="adLinkb2"></div>

Related

Settime out messing with onclick event in javascript

im trying to create a automatic image slider which also responds to an onclick function, for some odd reason the onclick event is pretty much doing nothinig i suspect its cause of the settime out as javascript is single threaded but im no master at javascript! could someone please tell me what i'm doing wrong stuck with this for the past two days! thank you!
var i = 0;
var starterimages= [];
var time = 3000;
var eventaction=0;
var timeoutId;
starterimages[0] = "https://i.pinimg.com/236x/f4/92/39/f492399e154bd9f564d7fc5299c19911--purple-rain-deep-purple.jpg";
starterimages[1] = "https://image.shutterstock.com/image-photo/purple-butterfly-isolated-on-white-260nw-44004850.jpg";
starterimages[2] = "https://www.birdscanada.org/images/inbu_norm_q_townsend.jpg";
var nextbutton=document.querySelector("#rightbutton");
nextbutton.addEventListener("click",rightbuttonclick);
var prevbutton=document.querySelector("#leftbutton");
nextbutton.addEventListener("click",leftbuttonclick);
function rightbuttonclick()
{
eventaction=1;
clearTimeout(timeoutId);
}
function leftbuttonclick()
{
eventaction=2;
clearTimeout(timeoutId);
}
function changeImg(){
document.getElementById('startersliders').src = starterimages[i];
if(eventaction==1)
{
i++;
if(i < starterimages.length - 1)
{document.getElementById('startersliders').src = starterimages[i];
eventaction=0;}
else
{
i=0;
document.getElementById('startersliders').src = starterimages[i];
eventaction=0;
}
}
else if(eventaction==2)
{
i--;
if(i== - 1)
{
i=3;
document.getElementById('startersliders').src = starterimages[i];
eventaction=0;
}
else
{
document.getElementById('startersliders').src = starterimages[i];
eventaction=0;
}
}
else if(eventaction==0){
if(i < starterimages.length - 1){
i++;
}
else {
i = 0;
}
}
// Run function every x seconds
timeoutId = setTimeout("changeImg()", time);
}
// Run function when page loads
window.onload=changeImg;
#staratersliders {
width: 10%;
height: 10%;
position: relative;
margin: 0% 0% 0% 0%;
}
<button class="button button3" id="leftbutton"> previous</button>
<img id="startersliders" />
<button class="button button3" id="rightbutton">next</button>
I got it all working in Firefox 51, buttons included. Just paste the whole thing in a blank page and save it with an .htm or .html extension.
<!DOCTYPE=HTML><html><meta charset="UTF-8">
<script>
var i = 0;
var starterimages= [];
var time = 3000;
var eventaction=0;
var timeoutId;
starterimages[0] = "https://i.pinimg.com/236x/f4/92/39/f492399e154bd9f564d7fc5299c19911--purple-rain-deep-purple.jpg";
starterimages[1] = "https://image.shutterstock.com/image-photo/purple-butterfly-isolated-on-white-260nw-44004850.jpg";
starterimages[2] = "https://www.birdscanada.org/images/inbu_norm_q_townsend.jpg";
function rightbuttonclick() {
eventaction = 1;
clearTimeout(timeoutId);
changeImg();
}
function leftbuttonclick() {
eventaction = 2;
clearTimeout(timeoutId);
changeImg();
}
function changeImg() {
if (eventaction == 1) {
if (i < starterimages.length - 1) {
i++;
document.getElementById('startersliders').src=starterimages[i];
eventaction = 0;
} else {
i = 0;
document.getElementById('startersliders').src=starterimages[i];
eventaction = 0;
}
} else if (eventaction == 2) {
i--;
if (i < 0) {
i = 2;
document.getElementById('startersliders').src=starterimages[i];
eventaction = 0;
} else {
document.getElementById('startersliders').src=starterimages[i];
eventaction = 0;
}
} else {
if (i < starterimages.length - 1) {
i++;
} else {
i = 0;
};
document.getElementById('startersliders').src=starterimages[i];
eventaction = 0;
}
timeoutId=setTimeout("changeImg()", time);
}
</script>
<style>
#startersliders {width: 10%;height: 10%;position: relative;margin: 0% 0% 0% 0%;}
</style>
<body onload="changeImg();">
<button class="button button3" id="leftbutton">previous</button>
<img id="startersliders">
<button class="button button3" id="rightbutton">next</button>
<script>
var nextbutton=document.querySelector("#rightbutton");
nextbutton.addEventListener("click",rightbuttonclick);
var prevbutton=document.querySelector("#leftbutton");
prevbutton.addEventListener("click",leftbuttonclick);
</script>
</body>
</html>
It won't work because this:
setTimeout("changeImg()", time);
Is invalid syntax for setTimeout. To fix it, just do this:
setTimeout(changeImg, time);
var nextbutton=document.querySelector("#rightbutton");
nextbutton.addEventListener("click",rightbuttonclick);
var prevbutton=document.querySelector("#leftbutton");
nextbutton.addEventListener("click",leftbuttonclick);
I copy/pasted the code into my machine and the above came up null because they need to be between script tags at the bottom of the body of the doc.
When the parser sees those at the top, it doesn't know what #rightbutton and #leftbutton are because it hasn't parsed the html in the body section yet so it comes back as a null element
just move them to the bottom of the body section after the html and put script /script tags around them and see what happens
You need to do both of the above, what Matthew Herbst said is correct and what Jack Bashford said is correct. Create a variable for the setTimeout
var mytimeinverval;
var mytimer;
mytimer=setTimeout(myfunctionname,mytimeinterval);
The function name inside the setTimeout doesn't get quotes or parenthesis.
If you put parenthesis in, it might fire instantly or who knows?
It still recognizes myfunctionname as a function without the parenthesis.
Putting quotes around it makes it a string-won't work in my experience.
I don't want credit, they answered it, just letting you know to do both.

javascript settimeout takes too much time than expected to excute the code

I have tried to make the code works fine in stackoverflow but when I added the javascript code, it has stopped.any way
I have this code:
showCharacters("hey, how are you");
function showCharacters(text) {
var charactersArray = new String(text).split('');
var i;
for (i = 0; i < charactersArray.length; i++) {
setCharacter(i, charactersArray);
}
deleteAll(i - 1);
}
function setCharacter(i, charactersArray) {
setTimeout(function() {
document.getElementById("characters").innerHTML = document.getElementById("characters").innerHTML + charactersArray[i];
}, 1000 * i);
}
function deleteAll(i) {
setTimeout(function() {
var text = document.getElementById("characters").innerHTML;
var charactersArray = new String(text).split('');
var charactersArrayLength = charactersArray.length - 1;
for (var j = charactersArrayLength; j >= 0; j--) {
charactersArray.splice(j, 1);
deleteCharacter(charactersArray.join(""), i + charactersArrayLength - j + 1);
}
}, (i + 1) * 1000);
}
function deleteCharacter(text, i) {
setTimeout(function() {
document.getElementById("characters").innerHTML = text;
}, 1000 * i);
}
#divContainer {
display: flex;
align-items: center;
float: right;
}
#characters {
font-weight: 700;
color: rgb(0, 0, 0);
font-size: 40px;
padding-top: 2px;
white-space: nowrap;
}
<div id="divContainer">
<h1 id="characters">
</h1>
</div>
I made the code to write one character every second and after complete the text it will delete one character every second,the problem is that after complete the text it will wait for a few seconds before starting deleting the characters.I did not do that.
I have followed the time value of settimeout method and everything is fine.
I want it to start deleting characters directly after complete the text.
any help please.
Dont line up app the timeouts in a row do them one after the other.
Here is how you should do it. I speed the time up a bit, but that matters not.
var text = "Add a new timeout as needed."
var div = document.createElement("div");
document.body.appendChild(div);
var textPos = 0;
function textAdd(){
div.textContent += text[textPos++];
if(textPos >= text.length){
setTimeout(clearText,1000);
}else{
setTimeout(textAdd,200);
}
}
function clearText(){
textPos --;
div.textContent = text.substr(0,textPos);
if(textPos === 0){
setTimeout(textAdd,1000);
}else{
setTimeout(clearText,200);
}
}
textAdd();
I stayed close to your code, the fix was actually quite simple, I marked it with THE FIX below.
// Replace spaces with non-breaking spaces so it does not stutter, and use global var
var text = "hey, how are you".replace(/ /g, String.fromCharCode(160));
showCharacters();
function showCharacters() {
var chars = new String(text).split('');
var i;
for (i = 0; i < chars.length; i++) {
setCharacter(i, chars);
}
deleteAll(i - 1);
}
function setCharacter(i, chars) {
setTimeout(function() {
document.getElementById("characters").innerHTML = document.getElementById("characters").innerHTML + chars[i];
}, 200 * i);
}
function deleteAll(i) {
setTimeout(function() {
var chars = new String(text).split('');
var len = chars.length - 1;
for (var j = len; j >= 0; j--) {
chars.splice(j, 1);
deleteCharacter(chars.join(""), i - j + 1); // THE FIX: don't add length here
}
}, (i + 1) * 200);
}
function deleteCharacter(text, i) {
setTimeout(function() {
document.getElementById("characters").innerHTML = text;
}, 200 * i);
}
#divContainer {
display: flex;
align-items: center;
float: right;
}
#characters {
font-weight: 700;
color: rgb(0, 0, 0);
font-size: 40px;
padding-top: 2px;
white-space: nowrap;
}
<div id="divContainer">
<h1 id="characters">
</h1>
</div>

.forEach method applying update to all items in array instead of individual item

I'm making a small exercise for some students of mine where I am automating a kind of 10 pin bowling game I have put it into a JsBin here https://jsbin.com/qilizo/edit?html,js,output. I don't know whether I am tired, stupid or it's just because I am working on a national holiday but something has me puzzled. When i start the game I prompt the user to set up a number of desired players. This automatically produces an object array of Players like so:
[{score: Array[10], spareCount: 0, strikeCount: 0, username: "Player 1"}, ...]
Now later I allow the user to play frames where each Player in our array has two throws... I collect the score and add it to the certain player's score array. However when I try to perform this action using a .forEach method the score I generate is applied to all items in my Players array (play the game and see). I have put my code in a jsBin and the problem is on line 109 : a.score[currentFrame - 1] = playFrame();
I have tried to amend my code but I can't work out why the current (or last) frame score is being applied to all Player objects! If you can understand my syntax error and explain why I would be most appreciative. Play the game (just click the button after setting the player numbers) and you will see what I mean...
Snippet:
var players,
currentFrame = 0,
currentThrow = 0;
// helper functions
// Accurate isNumber function... Thank you Crockford (see JavaScript: The Good Parts)
function isNumber(value) {
return typeof(value === 'number') && isFinite(value);
}
function frameStyle(k) {
var returnCssClass,
k = k + 1;
if (k < currentFrame) {
returnCssClass = 'played-frame';
} else if (k === currentFrame) {
returnCssClass = 'current-frame';
} else {
returnCssClass = null;
}
return returnCssClass;
}
function setUpPlayers(num) {
var tempArray = [],
tempName = 'Player ',
emptyScores = Array(10).fill([-1, -1]); // set default to -1 as a rubbish player may hit no pins!
for (var i = 0; i < num; i++) {
tempArray.push({
username: tempName + (i + 1),
score: emptyScores,
strikeCount: 0,
spareCount: 0
}); // the way I have named the tempName is technically an antipattern!
}
return tempArray;
}
function getTotals(scores) {
var totalScore = scores.reduce(function(a, b) {
return a + b.reduce(function(c, d) {
return (c + (c + ((d > 0) ? d : 0)));
}, 0);
}, 0);
return totalScore;
}
function displayScore(score) {
// toDo reformat!
var formatScore = score.map(function(a, b) {
if (a === -1) {
a = '-';
} else if (a === 10) {
a = 'X';
}
return a;
});
return formatScore;
}
function createGrid() {
// If only I was using ES6 I could have multi line support!
var playerLen = players.length,
scoresLen = players[0].score.length;
boards = '<div class="score-board">' +
'<!-- one row for each player -->';
// need to loop this through the players...
for (var i = 0; i < playerLen; i++) {
boards += '<div class="row">' +
'<!-- first cell is the name -->' +
'<div class="name">' + players[i].username + '</div>';
// need to loop this with the users scores
for (var k = 0; k < scoresLen; k++) {
boards += '<div class="game ' + frameStyle(k) + ' ">' + displayScore(players[i].score[k]) + '</div>';
}
// don't forget the total
boards += '<div class="player-total">' + getTotals(players[i].score) + '</div>';
boards += '</div>';
}
boards += '</div>';
boards += '<div>Current Frame: ' + currentFrame + '</div>';
boards += '<button type="button" onclick="startGame()">Start Game</button>';
// fill the holder....
document.getElementById('boardHolder').innerHTML = boards;
}
function startGame() {
if (currentFrame >= 10) {
announceWinner();
} else {
currentFrame++;
// do the throws for Each Player!
players.forEach(function(a, b) {
a.score[currentFrame - 1] = playFrame();
});
// update the grid
createGrid();
// recurrrrrrsion....
//startGame();
}
}
function throwBall(pinsStanding) {
// i know it isn't a ball
return Math.floor(Math.random() * (pinsStanding + 1));
}
function playFrame() {
// here we just create the array and determine if we have a strike or a spare!
var pinsStanding = 10,
frameScore = [],
frameThrows = 2,
pinsDown;
for(var i = 0; i < frameThrows; i++) {
pinsDown = throwBall(pinsStanding);
pinsStanding = pinsStanding - pinsDown;
// if it is the pinsStanding = 0 and it is the first throw - a strike!
if(pinsStanding === 0 && i === 1) {
pinsStanding = 10;
frameThrows = 3;
}
// what if it is a spare?
frameScore.push(pinsDown);
}
return frameScore;
}
function announceWinner() {
}
// kick it all off!!!
window.onload = function() {
// lets get some users....
players = prompt('Please enter the NUMBER of players?', 2);
// check we have a number...
if (isNumber(players)) {
players = setUpPlayers(players);
createGrid();
}
};
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
/* classes */
.score-board {
border: 1px solid #000;
}
.row {
display: block;
border-bottom: 1px solid #000;
}
.row:last-child {
border-bottom: none;
}
.row > div {
display: inline-block;
padding: 5px;
}
.game {
border-right: 1px solid #000;
}
.name {
background-color: #f5f5f5;
border-right: 1px solid #000;
}
.player-total {
text-align: right;
background-color: #d5eabb;
}
.played-frame {
background-color: #aee1e8;
}
.current-frame {
background-color: #ffc0cb;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<h1>Let's go bowling!</h1>
<div id="boardHolder">
</div>
</body>
</html>
Here is the bin!
https://jsbin.com/qilizo/edit?html,js,output
You need to call Array(10).fill([-1, -1]) inside for loop, because otherwise all objects will share the same score array:
function setUpPlayers(num) {
var tempArray = [],
tempName = 'Player ';
for (var i = 0; i < num; i++) {
tempArray.push({
username: tempName + (i + 1),
score: Array(10).fill([-1, -1]),// set default to -1 as a rubbish player may hit no pins!
strikeCount: 0,
spareCount: 0
}); // the way I have named the tempName is technically an antipattern!
}
return tempArray;
}
https://jsbin.com/yeyupiteyu/1/edit?html,js,output
In JavaScript objects are passed by reference, and since array is an object, if you declare emptyScores outside the loop and then assign it to every element of the array, all elements will share the same score array.
You have make new emptyScores array for each element, so you have to declare it inside the loop:
var tempArray = [],
tempName = 'Player ';
for (var i = 0; i < num; i++) {
var emptyScores = Array(10).fill([-1, -1]);
tempArray.push({
username: tempName + (i + 1),
score: emptyScores,
strikeCount: 0,
spareCount: 0
});
}

How to define a variable of multiple variables in JavaScript

I would like to know how can I define a bigger variable for a set of variables that I have in javascript: showFootnotesPanel();, showReferencesPanel();, showImagesPanel();, showInformationPanel();.
Would it be something like this?
function showPanel() {
var x = [showFootnotesPanel();showReferencesPanel();showImagesPanel();showInformationPanel();]
}
Update:
I have this function that used to open a side panel on the right side and color the content:
var els = document.getElementsByClassName('change-color'),
target = document.getElementsByClassName('resources'),
changeColor = function(a) {
elements = document.getElementsByClassName("note");
for (var i = 0; i < elements.length; i++) {
console.log(elements[i])
elements[i].style.backgroundColor = "";
}
target = a.getAttribute('href');
element = document.querySelector('[data-id="' + target.substring(1, target.length) + '"]');
element.style.backgroundColor = a.getAttribute('data-color');
};
for (var i = els.length - 1; i >= 0; --i) {
els[i].onclick = function() {
showFootnotesPanel();
changeColor(this);
}
Now I have 4 side panels that need to respond to the same script, and I thought that by defining something like showPanel() is showFootnotesPanel() or showReferencesPanel() or showImagesPanel() or showInformationPanel() I might simplify things, so the last line of the script would be this instead just:
els[i].onclick = function(){showPanel();changeColor(this);}
Update 2:
Or is it possible to do this with the logical operator OR?
els[i].onclick = function(){showFootnotesPanel(); || showReferencesPanel(); || showImagesPanel(); || showInformationPanel();changeColor(this);}
Update 3:
This is the new script that I am using to hide and show the panels:
function showPanel(myPanel) {
var elem = document.getElementById(myPanel);
if (elem.classList) {
console.log("classList supported");
elem.classList.toggle("show");
} else {
var classes = elem.className;
if (classes.indexOf("show") >= 0) {
elem.className = classes.replace("show", "");
} else {
elem.className = classes + " show";
}
console.log(elem.className);
}
}
function hideOthers(one, two, three, four) {
if (one > "") {
var elem1 = document.getElementById(one);
var classes = elem1.className;
elem1.className = classes.replace("show", "");
}
if (two > "") {
var elem2 = document.getElementById(two);
var classes = elem2.className;
elem2.className = classes.replace("show", "");
}
if (three > "") {
var elem3 = document.getElementById(three);
var classes = elem3.className;
elem3.className = classes.replace("show", "");
}
if (four > "") {
var elem4 = document.getElementById(four);
var classes = elem4.className;
elem4.className = classes.replace("show", "");
}
return;
}
And this is the script that calls the panels and highlights the text on them:
var els = document.getElementsByClassName('change-color'),
target = document.getElementsByClassName('resources'),
changeColor = function(a) {
elements = document.getElementsByClassName("note");
for (var i = 0; i < elements.length; i++) {
console.log(elements[i])
elements[i].style.backgroundColor = "";
}
target = a.getAttribute('href');
element = document.querySelector('[data-id="' + target.substring(1, target.length) + '"]');
element.style.backgroundColor = a.getAttribute('data-color');
};
for (var i = els.length - 1; i >= 0; --i) {
els[i].onclick = function() {
hideOthers('footnotes-section', 'references-section', 'images-section', 'information-section');
showPanel('references-section');
changeColor(this);
}
}
Thank you!
Updated with a final solution.
In javascript you can declare variables by this way:
var text = ""; // String variable.
var number = 0; //Numeric variable.
var boolValue = true; //Boolean variable.
var arrayValue = []; // Array variable. This array can contain objects {}.
var obj = {}; // Object variable.
Check this version of your code.
// var text = ""; => String variable.
// var number = 0; => Numeric variable.
// var boolValue = true; => Boolean variable.
// var arrayValue = []; => Array variable. This array can contain objects {}.
// var obj = {}; => Object variable.
// This section of code is only to explain the first question.
(function() {
function showFootnotesPanel() {
return 10; // Random value.
}
function showReferencesPanel() {
return 30; // Random value.
}
function showImagesPanel() {
return 50; // Random value.
}
function showInformationPanel() {
return 90; // Random value.
}
function showPanel() {
return [
showFootnotesPanel(), // Index = 0
showReferencesPanel(), // Index = 1
showImagesPanel(), // Index = 2
showInformationPanel() // Index = 3
];
}
var bigVariable = showPanel(); // bigVariable is array of numeric values.
// Using logical operator to check status of variable about this demo code.
if (bigVariable[0] === 10 || bigVariable[1] === 30) {
console.log("Hey, with these values can show the FootnotesPanel and ReferencesPanel.");
} else {
console.log("With the current values can't show anything...");
}
console.log(bigVariable);
})();
// https://jsfiddle.net/dannyjhonston/t5e8g22b/
// This section of code attempts to answer the question of this post.
(function() {
// This function can be executed when the page is loaded.
function showPanel(panels) {
var panel, panelVisible = "";
var selPanels = document.getElementById("selPanels");
// In panels array...
for (var i = 0; i < panels.length; i++) {
// panels[0] = "ReferencesPanel";
panel = document.getElementById(panels[i]); // Get in the DOM tag context of the panel to set in the variable "panel".
panelVisible = panel.getAttribute("data-visible"); // HTML5 data attribute.
if (panelVisible == "true") {
panel.setAttribute("class", "show");
} else {
panel.setAttribute("class", "hide");
}
}
}
// This function is for set panel visibilty.
function setPanel(panelId, status) {
panel = document.getElementById(panelId);
panel.setAttribute("data-visible", status);
// Calling the showPanel function to check in the DOM.
showPanel(["ReferencesPanel", "InformationPanel", "ImagesPanel", "FootnotesPanel"]);
}
// Binding the change event to the select tag.
selPanels.addEventListener("change", function() {
// Executes setPanel function with panelId and true to update the data-visible attribute in the DOM.
setPanel(this.options[this.selectedIndex].value, "true");
});
// Executes showPanel function with array argument with panels Id. You need to specify every panel that want to handle.
showPanel(["ReferencesPanel", "InformationPanel", "ImagesPanel", "FootnotesPanel"]);
})();
#global {
border: solid 1px #6291AD;
}
.tools {
background-image: linear-gradient(#FFFFFF, #8999CE);
}
#global div[data-visible] {
height: 80px;
padding: 5px 0;
}
#global div p {
padding: 10px;
}
#ReferencesPanel {
background-image: linear-gradient(#FFFFFF, #FD9A9A);
float: left;
width: 20%;
}
#InformationPanel {
background-image: linear-gradient(#FFFFFF, #A1C7F1);
float: left;
width: 80%;
}
#ImagesPanel {
background-image: linear-gradient(#C6E9FB, #FFF);
width: 100%;
}
#FootnotesPanel {
background-image: linear-gradient(#C6E999, #FFF);
width: 100%;
}
.clear {
clear: both;
}
.show {
display: block;
}
.hide {
display: none;
}
<div id="global">
<div class="tools">Show Panel:
<br />
<!-- Demo -->
<select id="selPanels">
<option value="">[SELECT]</option>
<option value="ReferencesPanel">ReferencesPanel</option>
<option value="InformationPanel">InformationPanel</option>
<option value="ImagesPanel">ImagesPanel</option>
<option value="FootnotesPanel">FootnotesPanel</option>
</select>
</div>
<!-- You need to set data-visible attribute with true or false to show or hide a panel. -->
<div id="ReferencesPanel" data-visible="false">
<p>References Panel</p>
</div>
<div id="InformationPanel" data-visible="false">
<p>Information Panel</p>
</div>
<div class="clear"></div>
<div id="ImagesPanel" data-visible="false">
<p>Images Panel</p>
</div>
<div id="FootnotesPanel" data-visible="false">
<p>Foot notes Panel</p>
</div>
</div>
I dont understand your question exactly, but if you want to define a variable that contains other variables then you can use an object.
e.g:
var footNotesPanel = true;
var referencesPanel = true;
var imagesPanel = true;
var showPanels = {
footNotesPanel: footNotesPanel,
referencesPanel: referencesPanel,
imagesPanel: imagesPanel
}
/*
Option 2 - for showing/hiding side panels
1 ) create all your panels as they would appear, with all the data, but hide them with display:none;
2 ) call show panel function to show a panel.
*/
var showPanel(panel_id) {
var panel_element = $("#" + panel_id); /*panel that you want to show ( is hidden atm but somewhere on the page */
if (!panel_element.length) {
return false; //no panel with this id currently on page
} else {
//check the panel id and do some custom editing if needed, eg.
if (panel_id == "main_side_panel") {
//add some additional classes to body element etc
}
panel_element.show();
//Or Another option that you probably are looking for is below
if (panel_id == "footnotes_panel") {
showFootnotesPanel();
} else if (panel_id == "images_panel") {
showImagesPanel();
}
}
}
// And use it like this:
<div id="footnotes_panel" onclick="showPanel('footnotes_panel')"></div>
// Or simply get the element id from `event.target` and use `showPanel()` without arguments.

How to add random delay spikes to this?

Hi I finally got my progress bar the way I want, is there a way to make it have delay spikes? like its actually loading data, for now this is just for looks on my website but I would like it to look authentic. heres the code. the max delay I would need and want is 500 milliseconds.
<html><head>
<style>
#adLinkb,
#adLinkb2 {
font-size: 12px;
color: #fff;
font-family:sans-serif;
}
</style>
</head>
<body>
<div id="adLinkb" style="border: 1px solid black;width:212;background-color:black;border-color:white"></div>
<br>
<div id="adLinkb2" style="border: 1px solid black;width:212;background-color:black;border-color:white"></div>
<script type="text/javascript">
function buildBar(id, callback) {
var currentAdb = 0;
var imgCtb = 70;
function cycleb() {
var output = '';
for (var i = 0; i < imgCtb; i++) {
output += i > currentAdb ? ' ' : '/';
}
output += '';
document.getElementById(id).innerHTML = output;
++currentAdb;
if (currentAdb == imgCtb) {
window.clearInterval(myInterval);
if (typeof callback == 'function') {
callback();
}
}
}
var myInterval = window.setInterval(cycleb, 100);
}
function callback1() {
buildBar('adLinkb2', callback2);
}
function callback2() {
//window.location... stuff here
alert('redirect should go here');
}
buildBar('adLinkb', callback1);
</script>
</body></html>
You can replace the setInterval with a setTimeout and re-schedule with a random timeout
window.setTimeout(cycleb,10+Math.random()*300);
the fiddle: http://jsfiddle.net/martijn/qqf90r3f/
alternative spike:
if(Math.random()>0.9)
{
// 10% change on a spike
window.setTimeout(cycleb,10+Math.random()*1000);
}
else{
window.setTimeout(cycleb,10+Math.random()*10);
}
http://jsfiddle.net/martijn/qqf90r3f/1/

Categories

Resources