You helped me get the draw function work properly. Here's the complete program, which works perfectly until the "draw" button is clicked. Instead of drawing a new image, the entire window vanishes. Any help greatly appreciated!
This code is formatted as instructed, 4 spaces per tab. I don't know any more details to add.
<!DOCTYPE html>
<html>
<head>
<title>Digital Holograms</title>
<style>
div {
float: left;
height: 580px;
width: 500px;;
padding: 0 10px;
}
#column1 {
background-color: #FFFFFF;
}
#column2 {
background-color: #FFFFFF;
width: 500px
}
</style>
</head>
<body>
<div id="column1">
<canvas id="my-canvas" width="500" height="500"></canvas>
<script>
let selFun = 0 // selected function to draw
// user may change this by selection box
let canvas = document.querySelector('#my-canvas')
let context = canvas.getContext('2d')
context.fillStyle = 'black'
function draw(n) {
let contourInterval = 1500
let contourWidth = 500
let fsize = 1000
let x0 = fsize / 2
let y0 = fsize / 2
for (j = 0, y = -y0; j < fsize; j++, y++) {
for (i = 0, x = -x0; i < fsize; i++, x++) {
let fun = 0
switch(n) {
case 0:
fun = (x*x + y*y)
break;
case 1:
fun = (x*x - y*y)
break;
default:
fun = (x*x + y*y)
}
if (Math.abs(fun % contourInterval) < contourWidth) {
context.fillRect(x+x0/2, y+y0/2, 1, 1)
}
}
}
document.write('<h4 style="text-align: center;">Hologram of z = x² + y²</h4>');
}
draw(selFun)
function getSelection() {
let selFun = document.getElementById("selectFunction").value
//document.write(selFun)
}
</script>
<h3>To view other holograms:</br>Select a function, then press draw</h3>
<select id="selectFunction" onchange="getSelection()">
<option value=0>z = x² + y²</option>
<option value=1>z = x² - y²</option>
</select>
<button type = "button";
onclick = draw(selFun)>Draw</button>
</div>
</body>
</html>
There a several glitches that are preventing this code working as intended.
1) The loss of content on button press
This is a result of an incorrect use of document.write() (which can only be effectively used by inline scripts to inset text as the page is loading. Running it on a loaded page causes document.open() to be executed, clearing the existing document. See: https://developer.mozilla.org/en-US/docs/Web/API/Document/write
The correct way to update information on the page is to change the innerText or innerHTML of an existing element, or insert a new element with the required text.
In my snippet I added the h4 tag, with an id of updatedTitle, to the html (initially with no content, which will be added by the script):
<h4 id="updatedTitle" style="text-align: center;"></h4>
The innerText of the tag is added by the last line of the draw() function:
document.getElementById("updatedTitle").innerText = `Hologram of ${equation}`;
Note, the template literal ${equation}, this was used to allow the equation to be updated when a new option is drawn, by fetching the markup for the equation from the element (shown later).
2) Drop Down changes not registering
After correcting point 1), there was still a problem: pressing the draw button failed to render a new graph. After some investigation with console.log()s at various parts of the execution cycle I determined that the onchange of the dropdown element was not being received by the javascript.
The reason for this turned out to be a case of very bad luck - the choice of the function name intended to handle the change: getSelection. It turns out that getSelection is a built-in method of the Window object and seemingly cannot be used as a user function name.
Changing the function name to readSelection() cured this problem;
(https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection)
3) Button onclick event argument not accessible
The button's onlick event calls the draw() function, and attempts to send selFun as an argument. As written, selFun is not accessible from the element.
Instead, the onlick was changed to simply call the draw() function without any argument.
selFun is declared, and assigned with 0, in the global scope of the script and so is accessible from function in the script. Thus the argument n used in the switch block of the draw() function can be replaced directly with selFun (and n also deleted from the function parameter):
4) modification to readSelection()
The original values of the option list items were 0 and 1, entered as (unquotted) numbers in the markup. Although this is allowed, the 0 and 1 are converted to strings when the value attribute is read regardless of whether they were quotted or not (much like the contents of a text input field). Javascript is good at coercing numbers from digit characters but I was getting a bug where selFun was not being read properly for the case statement. Formally setting selFun to an integer value cured this:
selFun = parseInt(document.getElementById("selectFunction").value);
Since readSelection is invoked each time the drop down changes, it is also the place to keep track of which equation should be used in the label on next draw. Hence the following line was included in the function:
equation = document.getElementById("selectFunction").children[selFun].innerText;
with equation being declared (and set to the dropdown initial state) in the global scope of the script, to be read and used to form a label, as discussed in 1) above.
5) Draw only working for first change of equation
Once the above changes were made, changing the dropdown and pressing the button resulted in the new equation being rendered. However, subsequent changes and attempts to draw did not appear to do much.
This was because the second equation was being drawn on top of the first and, once both equations were drawm further drawing didn's show any change.
The solution was to include a standard clear step at the start of the draw() function:
context.clearRect(0, 0, canvas.width, canvas.height);
6) Element accessibility
The entire script was moved to the foot of the html to allow all elements to load before running the script, this prevented some errors where the js was trying to access elements that did not yet exist.
The programme seems to work as intended now. I don't understand anything about the equation plots but they are most impressive and, should you add more to it in future, perhaps you will comment back here so I can have a look!
Working snippet:
let selFun = 0
let equation = document.getElementById("selectFunction").children[selFun].innerHTML; // to be used to update graph label;
let canvas = document.querySelector('#my-canvas');
let context = canvas.getContext('2d');
context.fillStyle = 'black';
function draw() {
// clear canvas'
context.clearRect(0, 0, canvas.width, canvas.height);
let contourInterval = 1500;
let contourWidth = 500;
let fsize = 1000;
let x0 = fsize / 2
let y0 = fsize / 2
for (j = 0, y = -y0; j < fsize; j++, y++) {
for (i = 0, x = -x0; i < fsize; i++, x++) {
let fun = 0
switch(selFun) {
case 0:
fun = (x*x + y*y);
break;
case 1:
fun = (x*x - y*y);
break;
default:
fun = (x*x + y*y);
} // end switch
if (Math.abs(fun % contourInterval) < contourWidth) {
context.fillRect(x+x0/2, y+y0/2, 1, 1)
} // end if;
} // next i;
} // next j;
const titleH4 = document.getElementById("updatedTitle");
document.getElementById("updatedTitle").innerText = `Hologram of ${equation}`;
} // end draw;
draw();
function readSelection() {
selFun = parseInt(document.getElementById("selectFunction").value);
equation = document.getElementById("selectFunction").children[selFun].innerText;
} // end readSelection function;
div {
float: left;
height: 580px;
width: 500px;;
padding: 0 10px;
}
#column1 {
background-color: #FFFFFF;
}
#column2 {
background-color: #FFFFFF;
width: 500px
}
select {
width: 200px;
height: 1.5em;
font-size: 2em;
border-radius: 5px;
background: cyan;
text-align: center;
}
button {
width: 100px;
height: 1.5em;
font-size: 2em;
}
<div id="column1">
<canvas id="my-canvas" width="500" height="500"></canvas>
<h3>To view other holograms:</br>Select a function, then press draw</h3>
<select id="selectFunction" onchange="readSelection()">
<option value="0">z = x² + y²</option>
<option value="1">z = x² - y²</option>
</select>
<button type = "button" onclick="draw()">Draw</button>
<h4 id="updatedTitle" style="text-align: center;"></h4>
</div>
edit
Regarding the appearance of the dropdown and button - they can be styled much like any other html element. I've added some arbitrary changes to their apperance by adding rules for select and button elements to the css. The elements can be given a class name if more specific styling is needed without affecting other elements of the same kind.
I don't know what your code is trying to do but when the button is pressed you are updating the source completely.
Here is that bad code :)
document.write('<h4 style="text-align: center;">Hologram of z = x² + y²</h4>');
Add it inside a div instead of writing it to the whole document.
document.getElementById("example").innerHTML = 'your codes';
Related
I am having an issue with page loading time. Currently right now I am running UBUNTU in Oracle Vm Virtual Box. I am using mozilla firefox as my browser and I am working on an etchasketch project from "The odin project".
My problem is the page loading time. The code takes a prompt at the start and generates a grid for the etch a sketch based on that prompt. I have not given it the minimum and maximum values (16 and 64) respectively, however any number when prompted at the beginning that is beyond 35 doesn't load or takes ages to load.
How do I speed up the process time? / why is it moving so slow? / how can I avoid this ? / is there a fix that I am over looking that can make this work a lot faster? / feel free to tackle any and all of those questions!
This is my HTML CODE:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8"/>
<title>
</title>
</head>
<body>
<div class="etchhead">
<p> Choose your grid size </p>
<input type = "text"></input>
<button id="startOver"> Clear Grid </button>
<p> Change color </p>
</div>
<div id="grid">
</div>
<script src="eas.js"></script>
</body>
</html>
And this is my CSS code:
p {
color: blue;
display: inline;
}
#grid {
display: grid;
width: 800px;
max-width: 800px;
height: 800px;
max-height: 800px;
line-height: 0;
}
.gridBox {
border: 1px solid black;
background-color: lightgrey
}
And this is my JAVASCRIPT code:
gridStart();
function gridStart(){
var boxes = 0
var selectBody = document.querySelector("#grid");
var addBox = document.createElement("div");
var boxCountStart = prompt("enter a number between 16 and 64");
var boxDimensions = (boxCountStart * boxCountStart);
function rowsAndColumns() {
var selectBody = document.querySelector("#grid");
var gridTemplateColumns = 'repeat('+boxCountStart+', 1fr)';
selectBody.style.gridTemplateColumns= gridTemplateColumns;
selectBody.style.gridTemplateRows= gridTemplateColumns;
};
function hoverColor(){
var divSelector = selectBody.querySelectorAll("div");
divSelector.forEach((div) => {
div.addEventListener("mouseover", (event) => {
event.target.style.backgroundColor = "grey";
});
});
};
rowsAndColumns();
for (boxes = 0; boxes < boxDimensions ; boxes++) {
var selectBody = document.querySelector("#grid");
var addBox = document.createElement("div");
addBox.classList.add("gridBox");
addBox.textContent = (" ");
selectBody.appendChild(addBox);
hoverColor();
};
};
There are two components to your issue. One is that you are repeatedly modifying the DOM in a loop. You can fix it by appending all your boxes to a DocumentFragment and then adding that to the DOM after your loop finishes. You are also calling hoverColor(); inside your loop which results in adding tons of event listeners that all do the same thing (since inside hoverColor you are adding a listener to every single div). You can fix both those issues like this:
var fragment = document.createDocumentFragment( );
for (var i = 0; i < boxDimensions ; i++) {
var addBox = document.createElement("div");
addBox.classList.add("gridBox");
addBox.textContent = (" ");
fragment.appendChild(addBox);
}
document.querySelector("#grid").appendChild( fragment );
hoverColor();
Here is a JSFiddle with your original code, and here is one with the modification.
You could also benefit from only having one event listener total. You don't need to loop and add an event listener to every div. Just add one to #grid and use event.target (like you already do, to find the div that the event originated from). Something like this:
function hoverColor(){
document.querySelector("#grid").addEventListener( 'mouseover', function ( event ) {
event.target.style.backgroundColor = "grey";
} );
}
I was always under the impression that rather than touching the DOM repeatedly, for performance reasons, we should use a documentFragment to append multiple elements to, and then append the fragment into the document once, rather than just repeatedly appending new elements one-by-one into the DOM.
I've been trying to use Chrome's dev tools to profile these two approaches, using this test page:
<button id="addRows">Add rows</button>
<table id="myTable"></table>
Test 1 uses this code to append 50000 new rows to the table:
let addRows = document.getElementById('addRows');
addRows.addEventListener('click', function () {
for (let x = 0; x < 50000; x += 1) {
let table = document.getElementById('myTable'),
row = document.createElement('tr'),
cell = document.createElement('td'),
cell1 = cell.cloneNode(),
cell2 = cell.cloneNode(),
cell3 = cell.cloneNode();
cell1.textContent = 'A';
cell2.textContent = 'B';
cell3.textContent = 'C';
row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);
table.appendChild(row);
}
});
Clicking the button while recording in Chrome's Timeline tool results in the following output:
Test 2 uses this code instead:
let addRows = document.getElementById('addRows');
addRows.addEventListener('click', function () {
let table = document.getElementById('myTable'),
cell = document.createElement('td'),
docFragment = document.createDocumentFragment();
for (let x = 0; x < 50000; x += 1) {
let row = document.createElement('tr'),
cell1 = cell.cloneNode(),
cell2 = cell.cloneNode(),
cell3 = cell.cloneNode();
cell1.textContent = 'A';
cell2.textContent = 'B';
cell3.textContent = 'C';
row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);
docFragment.appendChild(row);
}
table.appendChild(docFragment);
});
This has a performance profile like this:
The second, supposedly much faster alternative to the first, actually takes longer to run! I've run these tests numerous times and sometimes the second approach is slightly faster, and sometimes, as these images show, the second approach is slightly slower, but not once has there been any significant difference between the two approaches.
What is happening here? Are browsers optimized so well now that this makes no difference anymore? Am I using the profiling tools incorrectly?
I'm on Windows 10, with Chrome 57.0.2987.133
Well actually your test code just insert nodes and do not alter their content or CSS which would in fact force the rendering engine to a reflow.
I have prepared 3 tests to demonstrate this dramatic difference.
Simple DOM modificiation resulting Layout Trashing
Simple DOM modificiation through window.requestAnimationFrame()
Virtual DOM modification through document.createDocumentFragment()
Notes:
You might like to test on full screen.
In Firefox I have obtained even more dramatic results.
// Resets the divs
function resetLayout() {
divs = document.querySelectorAll('div');
speed.textContent = "Resetting Layout...";
setTimeout(function() {
each.call(divs, function(div) {
div.style.height = '';
div.offsetTop;
});
speed.textContent = "";
}, 16);
}
// print the result
function renderSpeed(ms) {
speed.textContent = ms + 'ms';
}
var divs = document.querySelectorAll('div'),
raf = window.requestAnimationFrame,
each = Array.prototype.forEach,
isAfterVdom = false,
start = 0;
// Reset the Layout
reset.onclick = resetLayout;
// Direct DOM Access
direct.onclick = function() {
isAfterVdom && (divs = document.querySelectorAll('div'), isAfterVdom = false);
start = performance.now();
each.call(divs, function(div) {
var width = div.clientWidth;
div.style.height = ~~(Math.random()*2*width+6) + 'px';
div.style.backgroundColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
});
// Render result
renderSpeed(performance.now() - start);
};
// Access DOM at the next frame by requestAnimationFrame
rAF.onclick = function() {
isAfterVdom && (divs = document.querySelectorAll('div'), isAfterVdom = false);
start = performance.now();
each.call(divs, function(div) {
var width = div.clientWidth;
// Schedule the write operation to be run in the next frame.
raf(function() {
div.style.height = ~~(Math.random()*2*width+6) + 'px';
div.style.backgroundColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
});
});
// Render result
raf(function() {
renderSpeed(performance.now() - start);
});
};
// Update the vDOM and access DOM just once by rAF
vdom.onclick = function() {
var sectCl = divCompartment.cloneNode(true),
divsCl = sectCl.querySelectorAll('div'),
dFrag = document.createDocumentFragment(),
width = divCompartment.querySelector('div').clientWidth;
isAfterVdom = true;
end = 0;
start = performance.now();
each.call(divsCl, function(div) {
div.style.height = ~~(Math.random()*2*width+6) + 'px';
div.style.backgroundColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
});
dFrag.appendChild(sectCl);
divCompartment.parentNode.replaceChild(dFrag, divCompartment);
// Render result
renderSpeed(performance.now() - start);
};
html {
font: 14px Helvetica, sans-serif;
background: black;
color: white;
}
* {
box-sizing: border-box;
margin-bottom: 1rem;
}
h1 {
font-size: 2em;
//word-break: break-word;
-webkit-hyphens: auto;
}
button {
background-color: white;
}
div {
display: inline-block;
width: 5%;
margin: 3px;
background: white;
border: solid 2px white;
border-radius: 10px
}
section {
overflow: hidden;
}
#speed {
font-size: 2.4em;
}
<body>
<h1>Updating 1000 DOM Nodes</h1>
<section>
<button id="reset">Reset Layout</button>
<button id="direct">Update Directly</button>
<button id="rAF">Update by rAF</button>
<button id="vdom">Update by vDOM</button>
<section id="speed"></section>
<section id="divCompartment">
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</section>
</body>
Sorry... Due to the 30000 character limit in the answers and the length of the previous one i have to place another one as an extension to my previous answer.
I guess everybody's heard that direct DOM access is no good... Yes that's what i had always been told and so believed in the correctness of the virtual DOM approach. Though i hadn't quite understood the fact that while both the DOM and vDOM are represented on the memory, how come one is faster than the other? Actually streching my test further i have come to believe that the real bottle neck boils down to the JS engine performance if you update the DOM properly.
Now lets imagine the case of having 1000 divs to be updated repeatedly on background-color and height CSS properties.
If you do this directly on DOM elements all you have to do is to keep a nodeList of these elements and simply alter their style.backgroundColor and style.heigth properties.
If you do this by a document fragment you have the apparent benefit of not touching the DOM multiple times, instead first you have to
clone the parent container of the 1000 div elements.
access the nodeList containing the divs like parent.children
perform necessary alterations on each div element,
create a document fragment
re-clone the previously cloned (step 1) parent container element and append it to a document fragment (or alternatively you may chose to clone the divs' container from the DOM if you need the fresh ones but this way or that way for each modification you have to clone them)
append the document fragment to the parent of div container in the DOM and remove the old div container. Basically a Node.replaceChild operation.
In fact for this test we don't need a document fragment since we are not creating new nodes but just updating the already existing ones. So we can skip the step 4 and at step 5 we can directly use the cloned copy of our divs container as a source to our replaceChild operation.
How to update DOM properly..? Definitely asynchronously. So as for the previous example if you move the direct update portion to an asynchronous timeline like setTimeout(_ => renderDirect(),0) it will be the fastest among all. But then repeatedly updating the dome can be a little tricky.
One way to achieve this is to repedeatly feed a setTimeout(_ => renderDirect(),0) with our DOM updates like.
for (var i = 0; i < cnt; i++) setTimeout(_ => renderDirect(divs,width),0);
In the above case the performance of the JS engine is very material on the results. If our code is too light, than multiple cycles will stack up on a single DOM update and we will observe only a few of them. In this particular case, we got to see only like 9 of the 50 updates.
So delaying each turn further might be a good idea. So how about;
for (var i = 0; i < cnt; i++) setTimeout(_ => renderDirect(divs,width),i*17);
Well this is much better, I've got 22 of the 50 updates actually painted on my screen. So it happens to be, if the delay is chosen to be long enough you'll have all the frames painted. But how much long is a problem. Since if it's too long you have idle time for your rendering engine and it resembles slow DOM update. So for this particular test, it turns out to be something like 29-30ms ish... is the optimal value to observe 50 separate DOM updates of all 1000 divs in 1400 ms. Well at least on my desktop with Chrome. You may observe something entirely different depending on the hardware or the browser.
So the setTimeout resolution doesn't look very promising to me. We have to automate this job. Lucky us, we have the right tool for this job. rAF to help again. I have come up with a helper function to abuse the rAF (requestAnimationFrame). We will update the 1000 divs all at once, in one go, by directly accessing the DOM at the next available animation frame. And... while we are still in the asynchronous timeline we will request another animation frame from within the currently executing callback. So another rAF is called from the callback of the rAF recursively. I named this function looper
var looper = n => n && raf(_ => (renderDirect(divs, width),looper(--n)));
well it's a bit of an ES6 code. So let me translate it into classing JS.
function looper(n){
if (n !== 0) {
window.requestAnimationFrame(function(){
renderDirect(divs,width);
looper(n-1);
});
}
}
Now everything should be automated.. It seems pretty cool and done in 1385ms.
So since now we are a little more knowledgeable we may play with the code.
// Resets the divs
function resetLayout() {
divs = document.querySelectorAll('div');
speed.textContent = "Resetting Layout...";
setTimeout(function() {
each.call(divs, function(div) {
div.style.height = '';
div.backcgoundColor = '';
});
speed.textContent = "";
}, 16);
}
// print the result
function renderSpeed(ms) {
speed.textContent = ms + 'ms';
}
function renderDirect(divs,width){
each.call(divs, function(div) {
div.style.height = ~~(Math.random()*2*width+6) + 'px';
div.style.backgroundColor = '#' + Math.random().toString(16).substr(-6);
});
// Render result
renderSpeed(performance.now() - start);
}
function renderByVDOM(sct,prt,wdt){
var //dFrag = document.createDocumentFragment();
divs = sct.children;
each.call(divs, function(div) {
div.style.height = ~~(Math.random()*2*wdt+6) + 'px';
div.style.backgroundColor = '#' + Math.random().toString(16).substr(-6);
});
//dFrag.appendChild(sct);
prt.replaceChild(sct, divCompartment);
// Render result
renderSpeed(performance.now() - start);
}
var divs = document.querySelectorAll('div'),
width = divs[1].clientWidth;
raf = window.requestAnimationFrame,
each = Array.prototype.forEach,
isAfterVdom = false,
start = 0,
cnt = 50;
// Reset the Layout
reset.onclick = resetLayout;
// Direct DOM Access
direct.onclick = function() {
var looper = n => n && raf(_ => (renderDirect(divs, width),looper(--n)));
isAfterVdom && (divs = document.querySelectorAll('div'), isAfterVdom = false);
start = performance.now();
//for (var i = 0; i < cnt; i++) setTimeout(_ => renderDirect(divs,width),i*29);
looper(cnt);
};
// Update the vDOM and access DOM just once by rAF
vdom.onclick = function() {
var sectCl = divCompartment.cloneNode(true),
parent = divCompartment.parentNode,
looper = n => n && raf(_ => (renderByVDOM(sectCl.cloneNode(true), parent, width),looper(--n)));
isAfterVdom = true;
start = performance.now();
looper(cnt);
};
html {
font: 14px Helvetica, sans-serif;
background: black;
color: white;
}
* {
box-sizing: border-box;
margin-bottom: 1rem;
}
h1 {
font-size: 2em;
-webkit-hyphens: auto;
}
button {
background-color: white;
}
div {
display: inline-block;
width: 5%;
margin: 3px;
background: white;
border: solid 2px white;
border-radius: 10px
}
section {
overflow: hidden;
}
#speed {
font-size: 2.4em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="index.css" rel="stylesheet" type="text/css" />
<script src="index.js" async></script>
</head>
<body>
<h1>Updating 1000 DOM Nodes</h1>
<section>
<button id="reset">Reset Layout</button>
<button id="direct">Update Directly</button>
<button id="vdom">Update by vDOM</button>
<section id="speed"></section>
<section id="divCompartment">
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</section>
</section>
</body>
</html>
So the tests look like direct access through rAF is better than cloning and working on the clone and replacing the old one with it. Particularly when a huge DOM chunk is replaced it seems to me that the GC (Garbage Collect) task gets involved in the middle of the job and things get a little sticky. I am not sure how it can be eliminated. Your ideas are most welcome.
A Side Note:
This test also shows that the current (Version 91.0.838.3) of the new chromium based Edge Browser is performing DOM renderings ~15% faster than the current (Version 89.0.4389.114) Chrome.
I'm not sure how exactly to interpret your profiler results but running it through benchmark.js test shows second option is faster in Chrome: https://jsbench.me/awj1gwhk9i/1
ALso faster in FF (although a bit less difference)
Background
(New to JS and 1st time using canvas)
I am trying to read a JSON file from https://analytics.usa.gov/ and display it using a canvas. I want just the first 8 records to be populated in a drop down.
I was successful in getting a dump of the file locally on my machine. Code is here (https://jsfiddle.net/uh8jamdo/)
What I was trying to do is :
1) Page Title from the data should be populated in Drop Down
2) When the User selects one and clicks submit. I want to display the Page Title, URL and active users of that particular Page Title.
Below is my attempt. Can some one please guide me. I have written code to display canvas, text and update the data.
window.onload = function() {
var button = document.getElementById("previewButton");
button.onclick = previewHandler;
}
function previewHandler() {
var canvas = document.getElementById("analytics");
var context = canvas.getContext("2d");
drawText(canvas, context);
}
// draws all the text, including the Analytics
function drawText(canvas, context) {
context.font = "50px serif";
context.fillStyle = "black";
context.font = "bold 1em sans-serif";
context.textAlign = "left";
context.fillText("No of People online on Govt Websites", 20, 40);
// draw the analytics!
selectObj = document.getElementById("site");
index = selectObj.selectedIndex;
var site = selectObj[index].value;
context.font = "italic 1.2em serif";
context.fillText(site, 30, 100);
}
function updateAnalytics(site) {
var siteSelection = document.getElementById("site");
// add all data to the site dropdown
for (var i = 0; i < site.length; i++) {
site = site[i];
// create option
var option = document.createElement("option");
option.text = site.text;
// strip any quotes out of the site so they don't mess up our option
option.value = site.text.replace("\"", "'");
// add option to select
siteSelection.options.add(option);
}
// make sure the top tweet is selected
siteSelection.selectedIndex = 0;
}
canvas {
border: 1px solid black;
}
<canvas width="600" height="200" id="analytics">
<p>You need canvas to see the Analytics Data</p>
<p>This example requires a browser that supports the HTML5 Canvas feature.</p>
</canvas>
<p>
<label for="site">Pick a Site</label>
<select id="site"></select>
</p>
<p>
<input type="button" id="previewButton" value="Preview">
</p>
</form>
</br>
<script src="https://analytics.usa.gov/data/live/top-pages-realtime.json">
</script>
You basically have it, but there are enough strange things that I figure I can modify your code and you can study what I've done. A few issues I spotted:
Instead of hardcoding a script into the html document, we can fetch the contents of URL's through XMLHttpRequest. You are going to run into some timing issues.
There is no real need to use form and submit these days. Modern web design will usually maintain a stateful object on the client, and will communicate with various back ends using things like XMLHttpRequest, above. By doing this, we don't have to redraw the page every time we get a response back from the server. When the user clicks submit, you can catch that event, but there is a protocol you need to follow (return false from the handler) to prevent the page from reloading and blowing away the user's selection. The user will not get to see your canvas, because you'll be reloading a fresh canvas every time. They also will not see their selection because you'll be resetting it after every submit.
We don't need to strip quotes when setting the javascript value. First, because these things will usually get escaped for you, but second, because it's actually easier in your case to just store the index of the selection. You really don't need value at all. It may cause issues if you use this modified value as a key.
Minimize the number of global variables. Javascript has really good support for closure, which is a powerful programming construct that allows us to limit the visibility of variables, among other things. This will make it a lot easier to test your code in the debugger because everything will be grouped in one place. (More of a style than an actual issue).
Make sure to clear out your canvas if you plan to reuse it. Successive calls to fillText will clobber the previous text.
There are plenty of other things we could explore, but hopefully this will get you started.
Also, it's great that you are doing all of this without resorting to external libraries, but you should also check them out -- javascript can do some pretty exciting things. I recommend D3.js
Finally, here is the revised javascript, which I believe does the things you've specified, and which takes into account the advice I've given:
(you can play with the jsfiddle, here:
https://jsfiddle.net/dancingplatypus/L92fq305/6/)
var site_analytics = {
run: function () {
var ANALYTICS_SITE = 'https://analytics.usa.gov/data/live/top-pages-realtime.json';
var elem_select = document.getElementById("site");
var elem_title = document.getElementById("site_title");
var elem_preview = document.getElementById("previewButton");
var site_data = null;
elem_preview.onclick = render_selection;
elem_select.onchange = render_selection;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
console.log('heya');
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
site_data = JSON.parse(xmlhttp.responseText);
sync_selector();
}
}
xmlhttp.open("GET", ANALYTICS_SITE, true);
xmlhttp.send();
function sync_selector() {
console.log('boyo');
elem_select.innerHtml = null;
if (site_data) {
for (var loop = 0; loop < Math.min(8, site_data.data.length); loop++) {
var item = site_data.data[loop];
var option = document.createElement('option');
option.text = item.page_title;
option.value = loop;
elem_select.add(option);
}
}
selected_index = (site_data.data.length > 0) ? 0 : null;
render_selection();
}
function render_selection() {
var index = elem_select.selectedIndex;
var item = site_data ? site_data.data[index] : null;
elem_title.innerText = item ? item.page_title : 'n/a';
var canvas = document.getElementById("analytics");
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
drawText(item, canvas, context);
};
// draws all the text, including the Analytics
function drawText(item, canvas, context) {
context.font = "50px serif";
context.fillStyle = "black";
context.font = "bold 1em sans-serif";
context.textAlign = "left";
context.fillText("No of People online on Govt Websites", 20, 40);
// draw the analytics!
context.font = "italic 1.2em serif";
context.fillText(item ? item.active_visitors : '', 30, 100);
}
}
};
window.onload = function () {
site_analytics.run();
};
I'm trying to create a simple slideshow effect. I have 10 images, and I've created a basic HTML page with 2 buttons to go to the right or left image. On clicking the button, the images change.
Now, I'm trying to add a basic fade functionality to the changing image. But the fade effect isn't getting displayed. When I put alerts, I notice that the fade is taking place, but without the alerts it is too fast to be visible. Also, it is happening on the previous image, instead of the next one.
<html>
<head>
<style>
.main {
text-align: center;
}
.centered {
display: inline-block;
}
#image {
border: solid 2px;
width: 500px;
height: 500px;
}
#number {
font-size: 30px;
}
</style>
<script>
function goLeft() {
var image = document.getElementById("image");
var pos = document.getElementById("number");
if(Number(pos.innerHTML)==1) {
image.src = "Images\\10.jpg"
pos.innerHTML = 10;
} else {
image.src = "Images\\" + (Number(pos.innerHTML)-1).toString() + ".jpg"
pos.innerHTML = (Number(pos.innerHTML)-1).toString();
}
for (var i=0; i<25; i++) {
setTimeout(changeOpacity(image, i), 1000);
}
}
function changeOpacity(image, i) {
alert(parseFloat(i*4/100).toString());
image.style.opacity = (parseFloat(i*4/100).toString()).toString();
}
function goRight() {
var image = document.getElementById("image");
var pos = document.getElementById("number");
if(Number(pos.innerHTML)==10) {
image.src = "Images\\1.jpg"
pos.innerHTML = 1;
} else {
image.src = "Images\\" + (Number(pos.innerHTML)+1).toString() + ".jpg"
pos.innerHTML = (Number(pos.innerHTML)+1).toString();
}
for (var i=0; i<25; i++) {
setTimeout(changeOpacity(image, i), 1000);
}
}
</script>
</head>
<body>
<div class="main">
<div class="centered">
<img id="image" src="Images\1.jpg">
</div>
</div>
<div class="main">
<div class="centered">
<span id="number">1</span>
</div>
</div>
<div class="main">
<div class="centered">
<button onclick="goLeft()" style="margin-right:50px;">Go Left</button>
<button onclick="goRight()" style="margin-left:50px;">Go Right</button>
</div>
</div>
</body>
The problem is this block of code that is in your goLeft method, and goRight method:
for (var i=0; i<25; i++) {
setTimeout(changeOpacity(image, i), 1000);
}
You are creating 25 timers that, and each timer will execute approximately 1 second later.
Creating animations is best left to the CSS.
In your CSS add:
#image {
transition: opacity 0.5s ease;
}
And then in your JavaScript, simply: image.style.opacity = 1.0;
When the opacity changes, CSS will automatically transition the opacity length at the speed defined in the css, e.g 0.5s. Feel free to experiment.
I also added a jsfiddle here: http://jsfiddle.net/dya7L8wq/
You misunderstood setTimeout and the for loop.
Norman's answer provides a good solution with CSS, but he doesn't talk too much about why your code is not working. So I'd like to explain.
for (var i=0; i<25; i++) {
setTimeout(changeOpacity(image, i), 1000);
}
You assumption is:
invoke changeOpacity(image, 0) after 1 second
invoke changeOpacity(image, 1) 1 second after step 1
invoke changeOpacity(image, 2) 1 second after step 2
invoke changeOpacity(image, 3) 1 second after step 3
....
And the last step is invoking changeOpacity(image, 24) 1 second after previous step.
What actually happens is:
The loop is finished almost immediately!
In each iteration, setTimeout queues an asynchronous function invocation, and it's done! That says, it will return right away, rather than wait until changeOpacity returns.
And then, after about 1 second, changeOpacity fires 25 times almost at the same time, because you queued it 25 times in the for loop.
Another problem here is: in changeOpacity invocations, passed-in parameter i are not 1, 2, 3...., they all have the same value that causes for loop to exit (1 second ago) - 25, because JS doesn't have a block scope prior to ES6 (in ES6 we have keyword let for it).
In a pure JS solution, to ensure the time sequence we'd usually queue next invocation at the end of every step:
function changeOpacity() {
// do something here
// before the function returns, set up a future invocation
setTimeout(changeOpacity, 1000)
}
Here's an example to print a list of numbers from 1 to 5:
var go = document.getElementById('go')
var op = document.getElementById('output')
var i = 0
function printNum() {
var p = document.createElement('p')
p.innerHTML = ++i
op.appendChild(p)
// next step
if(i < 5) {
setTimeout(printNum, 500)
}
}
go.onclick = printNum
<button id="go">GO</button>
<div id="output"></div>
Why use pure JavaScript?
Use jQuery.
It has a pretty neat fadeTo() function and a useful fadeIn() function.
Might wanna use that ;)
I am trying to get a sound file to play faster in order to keep up with the text reveal in the following code. The sound works (in Firefox, anyway), but it only seems to play one instance of the file at a time.
I'd like to have each letter pop onto the screen accompanied by the popping sound. Right now the popping sound is sort of random, and not timed to play with each letter.
I'm wondering if I need to have multiple instances of the sound object, and how to do that.
I already shortened the sound file as much as I could, and the length of the file is shorter than the setTimeout interval I'm using. It just won't overlap multiple copies of the same sound file, for some very good reason that I don't know, I'm sure.
Here is the whole code:
(I tried to JSFiddle it, but couldn't get that to work (I'll save that question for a later date))
<html>
<head>
<style>
#display {
color: white;
font-size: 150%;
padding: 2em 5em;
min-height: 600px;
max-width: 600px;
margin-left: auto;
margin-right: auto;
}
body {
background-color: black;
padding: 0;
margin:0;
}
</style>
<script>
var text = "Test String... 1, 2, 3; Everything seems to be working, but the sound is lagging.";
var charDelay = 40; // Sets the delay time for the character loop
function loadText() {
var i = 0; // Character counter
var myPud = new Audio("http://southernsolutions.us/audio/pud03.ogg");
var displayBox = document.getElementById("display");
displayBox.innerHTML = "<p>";
textLoop();
function textLoop() {
if (i == text.length){ // This condition terminates the loop
displayBox.innerHTML += "</p>";
return;
} else if (i < text.length) { // This condition appends the next character
displayBox.innerHTML += text[i];
i++;
myPud.play();
setTimeout(function(){return textLoop()}, charDelay);
}
}
}
window.onload = function(){loadText()};
</script>
</head>
<body>
<div id="display"></div>
</body>
</html>
I'd suggest that you make the sound loop a little longer, say 1 second. Then, control the sound playing through event listeners so that once the text has finished, you stop the sound playing.
Trying to do it as you're doing it now, you could speed up the sound with how its playing in the audio file. This should give better results. That, or slow down the time out.
Below is some code that I've tested which would let you do it through event listeners. The results are similar to what you had, but if you took your audio file, increased it to 1 second and changed it up to have 24 clicks in there, you'd get the exact effect you were looking for.
Edit: I've also updated the below to take into account the comments.
<script>
var text = "Test String... 1, 2, 3; Everything seems to be working, but the sound is lagging.";
var charDelay = 40; // Sets the delay time for the character loop
function loadText() {
var i = 0; // Character counter
var myPud = new Audio("http://southernsolutions.us/audio/pud03.ogg");
var displayBox = document.getElementById("display");
// Toggle for whether to loop
var stillPlay = true;
displayBox.innerHTML = "<p>";
// Listen for when it ends
myPud.addEventListener("ended", onAudioComplete);
// Begin playing
myPud.play();
// Start the loop
textLoop();
function textLoop() {
if (i == text.length){ // This condition terminates the loop
displayBox.innerHTML += "</p>";
// If we're at the end, we want to stop playing
stillPlay = false;
// Rather than duplicate code, jump straight into the complete function
onAudioComplete(null);
return;
} else if (i < text.length) { // This condition appends the next character
displayBox.innerHTML += text[i];
i++;
// Direct reference to the function to avoid more anony. functions
setTimeout(textLoop, charDelay);
}
}
// On audio complete
function onAudioComplete(e){
// Can we still play? If so, play
if(stillPlay){
myPud.play();
} else {
// Otherwise, remove the event listener, stop and null out.
myPud.removeEventListener("ended", onAudioComplete);
myPud.stop();
myPud = null;
}
}
}
window.onload = loadText;
</script>