Stop bar animation with jQuery/javascript - javascript

Completely new to JS and jQuery here. The code iterates through each one of the bars and when you press the Reset button, it should shrink the bars down to zero. However, I am trying to get this bar graph animation to stop but once you press the button, it goes through the animation and resets back again to where it was before. Any help would be appreciated!
function barGraph(data) {
//Create graph
var graph = document.createElement("div");
graph.id = "barGraph";
//inserting bar graph before previous 'label' div
const target = document.querySelector('#labels');
target.parentNode.insertBefore(graph, labels);
//Styling for graph
graph.style.position = "relative";
graph.style.marginTop = "20px";
graph.style.height = "500px";
graph.style.backgroundColor = "Gainsboro";
graph.style.borderBottomStyle = "solid";
graph.style.borderBottomWidth = "1px";
graph.style.overflow = "hidden";
//Iterating through each bar
var position = 50;
var width = 75;
for (i = 0; i < data.length; i += 1) {
var spendData = data[i];
var bar = document.createElement("div");
//set a unique id for each of the bars
bar.id = data[i].category;
//Styling for bar
bar.style.position = "absolute";
bar.style.left = position + "px";
bar.style.width = width + "px";
bar.style.backgroundColor = spendData.color;
bar.style.height = (spendData.amount) / 5 + "px";
bar.style.bottom = "0px";
bar.innerHTML = "$" + spendData.amount;
bar.style.fontSize = "11px";
bar.style.color = "Azure";
bar.style.fontWeight = "800";
bar.style.fontFamily = "Arial, Helvetica, sans-serif";
bar.style.textAlign = "center";
bar.style.padding = "1em";
//Appending to the graph
graph.appendChild(bar);
//Set bar width
position += (width * 2);
}
return graph;
}
window.onload = function() {
var data = [{
category: "Food and Dining",
amount: "2005.00",
color: "CadetBlue"
},
{
category: "Auto and Transport",
amount: "1471.31",
color: "CornflowerBlue"
},
{
category: "Shopping",
amount: "892.86",
color: "DarkCyan"
},
{
category: "Bills and Utilities",
amount: "531.60",
color: "DarkSeaGreen"
},
{
category: "Mortgage",
amount: "1646.00",
color: "LightSeaGreen"
},
{
category: "Entertainment",
amount: "179.52",
color: "YellowGreen"
}
];
document.getElementById("resetGraph").addEventListener("click", function() {
for (i = 0; i < data.length; i++) {
var bar = document.getElementById(data[i].category);
if (bar) {
bar.animate({
"height": "0px",
"padding": "0px"
}, 2000);
}
}
});
var graph = barGraph(data);
//document.div.appendChild(graph);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="labels"></div>
<button id="resetGraph">Reset graph</button>
<script src="js/spending-graph.js"></script>

Dom's animate() function will return an AnimationPlaybackEvent object. And we can use onFinish method to reset the height and width of the dom element or can hide it.
Can you please add following lines to your code after bar.animate() function.
.onfinish=function(e){
e.currentTarget.effect.target.style.visibility ="hidden"
};
like below snippet.
bar.animate({
"height": "0px",
"padding": "0px"
}, 2000).onfinish=function(e){
e.currentTarget.effect.target.style.visibility ="hidden"
};

Updated
Interesting question! AFAICT the problem is that you've mixed up jQuery's .animate() with the native Javascript .animate().
Your question is tagged jQuery-animate, you mention it explicitly, and the format of the parameter you are passing to .animate() is exactly what jQuery expects.
But your animate code is running against an HTML DOM element, not a jQuery element:
// bar here is an HTML DOM Element, not a jQuery object:
var bar = document.getElementById(data[i].category);
// That means this will run JS .animate, not jQuery's:
bar.animate( ... );
If you simply change that to run against a jQuery object, it works (almost) as expected:
var bar = $('#' + data[i].category);
bar.animate( ... );
I say almost because there is another problem:
bar.id = data[i].category;
This creates HTML IDs from your plain English categories, which include whitespace, like "Food and Dining". According to the spec:
id's value must not contain whitespace (spaces, tabs etc.).
And at least when trying to use IDs with spaces as jQuery selectors, this matters, and it does not work. So instead let's just use the array index, which is also guaranteed to be unique, with a prefix so we know what we're referring to:
bar.id = 'bar-' + i;
Here's a working snippet with those 2 changes.
Note: the last document.div.appendChild(graph); was throwing an error - maybe this was a debugging attempt, it isn't necessary and I've commented it out here.
function barGraph(data) {
//Create graph
var graph = document.createElement("div");
graph.id = "barGraph";
//inserting bar graph before previous 'label' div
const target = document.querySelector('#labels');
target.parentNode.insertBefore(graph, labels);
//Styling for graph
graph.style.position = "relative";
graph.style.marginTop = "20px";
graph.style.height = "500px";
graph.style.backgroundColor = "Gainsboro";
graph.style.borderBottomStyle = "solid";
graph.style.borderBottomWidth = "1px";
graph.style.overflow = "hidden";
//Iterating through each bar
var position = 50;
var width = 75;
for (i = 0; i < data.length; i += 1) {
var spendData = data[i];
var bar = document.createElement("div");
//set a unique id for each of the bars
// UPDATED - category includes spaces, just use array index
// bar.id = data[i].category;
bar.id = 'bar-' + i;
//Styling for bar
bar.style.position = "absolute";
bar.style.left = position + "px";
bar.style.width = width + "px";
bar.style.backgroundColor = spendData.color;
bar.style.height = (spendData.amount) / 5 + "px";
bar.style.bottom = "0px";
bar.innerHTML = "$" + spendData.amount;
bar.style.fontSize = "11px";
bar.style.color = "Azure";
bar.style.fontWeight = "800";
bar.style.fontFamily = "Arial, Helvetica, sans-serif";
bar.style.textAlign = "center";
bar.style.padding = "1em";
//Appending to the graph
graph.appendChild(bar);
//Set bar width
position += (width * 2);
}
return graph;
}
window.onload = function() {
var data = [{
category: "Food and Dining",
amount: "2005.00",
color: "CadetBlue"
},
{
category: "Auto and Transport",
amount: "1471.31",
color: "CornflowerBlue"
},
{
category: "Shopping",
amount: "892.86",
color: "DarkCyan"
},
{
category: "Bills and Utilities",
amount: "531.60",
color: "DarkSeaGreen"
},
{
category: "Mortgage",
amount: "1646.00",
color: "LightSeaGreen"
},
{
category: "Entertainment",
amount: "179.52",
color: "YellowGreen"
}
];
document.getElementById("resetGraph").addEventListener("click", function() {
for (i = 0; i < data.length; i++) {
// UPDATED: 1. use new format ID without spaces
// UPDATED: 2. use jQuery selector/animation
// UPDATED: 3. use bar.length to test if selector matched anything
var bar = $('#bar-' + i);
if (bar.length) {
bar.animate({
"height": "0px",
"padding": "0px"
}, 2000);
}
}
});
var graph = barGraph(data);
//document.div.appendChild(graph);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="labels"></div>
<button id="resetGraph">Reset graph</button>
So what is happening in your original code? I am not sure. It is the native Javascript .animate() that is running, not jQuery's. The first parameter of the Javascipt .animate() method should be:
Either an array of keyframe objects, or a keyframe object whose properties are arrays of values to iterate over.
Your code is passing an object, not an array, so .animate() will expect the latter, "a keyframe object". The Keyframe Formats spec gives a little more detail and some examples for what "a keyframe object" looks like:
element.animate({
opacity: [ 0, 1 ], // [ from, to ]
color: [ "#fff", "#000" ] // [ from, to ]
}, 2000);
Your object does not match this format though - each attribute is just a string, not an array of start/stop values. The Keyframe docs also describe Implicit to/from keyframes:
In newer browser versions, you are able to set a beginning or end state for an animation only (i.e. a single keyframe), and the browser will infer the other end of the animation if it is able to.
My guess is this is what is happening, somehow? The browser is inferring an implicit end frame of the start values?
I tried to update your code to use the right Keyframe format, so you can use the native .animate() and skip jQuery all together, but it does not work - the bars reset to their original height after the animation, just like in your original code, I don't know why:
document.getElementById("resetGraph").addEventListener("click", function() {
var bar, startHeight;
for (i = 0; i < data.length; i++) {
bar = document.getElementById('bar-' + i);
if (bar) {
startHeight = window.getComputedStyle(bar).height;
bar.animate({
height: [startHeight, '0px'],
padding: ['1em', '0']
}, 2000);
}
}
});

Related

Smoothly change text and width on hover

So I have a span element whose textContent changes when I hover over it.
I want the old text to fade out, then fade in the new text.
Also, since the new text is longer than the old one, the width of the span needs to increase smoothly to the new value.
The solution below basically does what I want, but I am not satisfied with it for two reasons:
It splits the animation effect in two Animations that are played one after another.
This is not elegant and it causes a slight glitch in some browsers (Chrome and Edge, but not Firefox) at the point where the first animation finishes.
Determining the old and new width "manually", by simply changing the text and using getComputedStyle, also seems quite ugly.
Also I'm not sure it will always work because getComputedStyle might not return the width in pixels.
Concerning (1), there is a different solution where I only have one Animation and the text gets changed in the middle using setTimeout.
This doesn't have the glitch, but it is likewise not elegant.
Question: What is the best way to achieve the effect described above?
Below is my current solution:
const initialText = "Hover here";
const finalText = "Text changed on hover";
const dur = 1500; // in milliseconds
const element = document.getElementById("my-element");
element.textContent = finalText;
const finalWidth = parseFloat(window.getComputedStyle(element).width);
element.textContent = initialText;
const initialWidth = parseFloat(window.getComputedStyle(element).width);
const intermediateWidth = ( initialWidth + finalWidth ) / 2;
const keyframes_0 = new KeyframeEffect(
element,
[{ opacity: 1, width: initialWidth + "px" }, { opacity: 0, width: intermediateWidth + "px" }],
{ duration: dur / 2 }
);
const keyframes_1 = new KeyframeEffect(
element,
[{ opacity: 0, width: intermediateWidth + "px" }, { opacity: 1, width: finalWidth + "px" }],
{ duration: dur / 2 }
);
const animation_0 = new Animation( keyframes_0, document.timeline );
const animation_1 = new Animation( keyframes_1, document.timeline );
element.addEventListener('mouseenter', () => {
animateTextChange(element, animation_1, animation_0, finalText, 1.0);
});
element.addEventListener('mouseleave', () => {
animateTextChange(element, animation_0, animation_1, initialText, -1.0);
});
function animateTextChange(elem, anim0, anim1, text, rate) {
if( anim0.playState === "running" ) {
anim0.onfinish = () => { };
anim0.playbackRate = rate;
anim0.play();
} else {
anim0.onfinish = () => { };
anim1.onfinish = () => {
elem.textContent = text;
anim0.playbackRate = rate;
anim0.play();
};
anim1.playbackRate = rate;
anim1.play();
}
}
<span id="my-element" style="display:inline-block; white-space:nowrap; overflow:clip">
Hover here
</span>
… more text

Can I add class to dynamically created two.js element?

I am using the code showed below to create 46 small circles within a wrapper (div) draw-shapes;
let elem = document.getElementById('draw-shapes');
let params = { width: 1024, height: 768 };
let two = new Two(params).appendTo(elem);
for (let i = 1; i < 47; i++) {
circle = two.makeCircle(x, y, radius);
circle.fill = 'green';
circle.stroke = 'white';
circle.linewidth = 1;
circle.id = i;
}
All drawings are made with the Two.js library. I read in the documentation I can change the id of the created element, but I also need to assign a class to each element. I have tried everything from pure js setAttribute to jQuery .attr and .addClass methods, but none of them worked, so I started to wonder if this is even possible to do? If someone knows a way, please let me know how. Thank.
There is not internal utility or property to get to the DOM node of each Two element.
But the id you specify is indeed added as two-<specified-id> to the actual node.
So you can use the normal document.getElementById.
So in your case
let elem = document.getElementById('draw-shapes');
let params = {
width: 300,
height: 300
};
let two = new Two(params).appendTo(elem);
for (let i = 1; i < 20; i++) {
const circle = two.makeCircle(i * 10, i * 10, 40);
circle.fill = 'green';
circle.stroke = 'white';
circle.linewidth = 1;
circle.id = `two-circle-${i}`;
}
two.update();
// add classname to every fifth element;
for (let i = 1; i < 20; i += 5) {
const circleNode = document.getElementById(`two-circle-${i}`);
circleNode.classList.add('classname');
circleNode.addEventListener('mouseover', function() {
const path = two.scene.getById(this.id)
path.scale = 1.2;
two.update();
});
circleNode.addEventListener('mouseout', function() {
const path = two.scene.getById(this.id)
path.scale = 1;
two.update();
});
}
.classname {
stroke-width: 5;
stroke: red;
fill:yellow;
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/two.js/0.6.0/two.js"></script>
<div id="draw-shapes"></div>

Use the HoverTool in BokehJS

I wrote some javascript to create a correlation plot in BokehJS (everything happens in the client, I can't use the Python Bokeh package).
Now, I would like to add a HoverTool to display tooltips when the user hovers over the squares, but I can't find documentation or examples on how to do this. I started looking at the coffeescript source and found relavant pieces, but I don't really understand how to integrate them.
Any help finding documentation or examples about how to use the HoverTool in pure BokehJS would be great.
This is a pure javascript version that works with Bokeh 0.12.4.
It shows how to use grid plot, with separate hovers over each set of data.
The {0.01} in the hover object is used to format the values to 2 decimal places.
var plt = Bokeh.Plotting;
var colors = [
'#ee82ee', '#523ebf', '#9bc500', '#ffb600', '#f50019', '#511150',
'#8b38fa', '#2e792a', '#ffef00', '#ff7400', '#a90064', '#000000'
]
function circlePlots(xyDict, plot_width, plot_height, title) {
// make the plot and add some tools
var tools = "pan,crosshair,wheel_zoom,box_zoom,reset";
var p = plt.figure({
title: title,
plot_width: plot_width,
plot_height: plot_height,
tools: tools
});
// call the circle glyph method to add some circle glyphs
var renderers = [];
for (var i = 0; i <= 3; i += 1) {
// create a data source
var thisDict = {
'x': xyDict['x'],
'y': xyDict['y'][i],
'color': xyDict['color'][i]
}
var source = new Bokeh.ColumnDataSource({
data: thisDict
});
var r = p.circle({
field: "x"
}, {
field: 'y'
}, {
source: source,
fill_color: colors[i],
fill_alpha: 0.6,
radius: 0.2 + 0.05 * i,
line_color: null
});
renderers.push(r);
}
var tooltip = ("<div>x: #x{0.01}</div>" +
"<div>y: #y{0.01}</div>" +
"<div>color: #color</div>");
var hover = new Bokeh.HoverTool({
renderers: renderers,
tooltips: tooltip
});
p.add_tools(hover);
return p
}
var pageWidth = 450;
var plotCols = 2;
var plots = [];
var plotWidth = Math.floor(pageWidth / plotCols)
if (plotWidth > 600) {
plotWidth = 600
}
var plotHeight = Math.floor(0.85 * plotWidth)
for (var i = 0; i < plotCols; i += 1) {
// set up some data
var M = 20;
var xyDict = {
y: [],
color: []
};
for (var j = 0; j <= 4; j += 1) {
xyDict['x'] = [];
xyDict['y'].push([]);
xyDict['color'].push([]);
for (var x = 0; x <= M; x += 0.5) {
xyDict['x'].push(x);
xyDict['y'][j].push(Math.sin(x) * (j + 1) * (i + 1));
xyDict['color'][j].push(colors[j]);
}
}
var title = "Sin(x) Plot " + (i + 1).toString();
var p = circlePlots(xyDict, plotWidth, plotHeight, title);
plots.push(p)
};
plt.show(plt.gridplot([plots], sizing_mode = "stretch_both"));
<link href="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.4.min.css" rel="stylesheet" />
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.4.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-api-0.12.4.min.js"></script>
First to use hover in bokeh you must add it as a tool and then personalise it to show what will be shown on hover. Look at this US Unemployment example from the bokeh docs
TOOLS = "hover,save"
p = figure(title="US Unemployment (1948 - 2013)",
x_range=years, y_range=list(reversed(months)),
x_axis_location="above", plot_width=900, plot_height=400,
toolbar_location="left", tools=TOOLS)
hover = p.select(dict(type=HoverTool))
hover.tooltips = OrderedDict([
('date', '#month #year'),
('rate', '#rate'),
])

How do i change default orientation in infovis spacetree?

I'm trying to change the default orientation in a space tree but can't figure out where to add:
st.switchPosition("top", "animate", {
onComplete: function() {
alert('completed!');
}
});
So that the tree will start from the top instead of the default of right.
In the examples i've seen, the switchPosition is only used with an event handler, which i do not intend to have.
So in the example (taken from the infovis site:Infovis - spacetree ), where should i add the code (or any code) in order to change the default orientation?
var labelType, useGradients, nativeTextSupport, animate;
(function() {
var ua = navigator.userAgent,
iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
typeOfCanvas = typeof HTMLCanvasElement,
nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
textSupport = nativeCanvasSupport
&& (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
//I'm setting this based on the fact that ExCanvas provides text support for IE
//and that as of today iPhone/iPad current text support is lame
labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
nativeTextSupport = labelType == 'Native';
useGradients = nativeCanvasSupport;
animate = !(iStuff || !nativeCanvasSupport);
})();
var Log = {
elem: false,
write: function(text){
if (!this.elem)
this.elem = document.getElementById('log');
this.elem.innerHTML = text;
this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
}
};
function init(){
//init data
var json = {....removed due to space here in the group....}
//end
//A client-side tree generator
var getTree = (function() {
var i = 0;
return function(nodeId, level) {
var subtree = eval('(' + json.replace(/id:\"([a-zA-Z0-9]+)\"/g,
function(all, match) {
return "id:\"" + match + "_" + i + "\""
}) + ')');
$jit.json.prune(subtree, level); i++;
return {
'id': nodeId,
'children': subtree.children
};
};
})();
//Implement a node rendering function called 'nodeline' that plots a straight line
//when contracting or expanding a subtree.
$jit.ST.Plot.NodeTypes.implement({
'nodeline': {
'render': function(node, canvas, animating) {
if(animating === 'expand' || animating === 'contract') {
var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
var width = nconfig.width, height = nconfig.height;
var algnPos = this.getAlignedPos(pos, width, height);
var ctx = canvas.getCtx(), ort = this.config.orientation;
ctx.beginPath();
if(ort == 'left' || ort == 'right') {
ctx.moveTo(algnPos.x, algnPos.y + height / 2);
ctx.lineTo(algnPos.x + width, algnPos.y + height / 2);
} else {
ctx.moveTo(algnPos.x + width / 2, algnPos.y);
ctx.lineTo(algnPos.x + width / 2, algnPos.y + height);
}
ctx.stroke();
}
}
}
});
//init Spacetree
//Create a new ST instance
var st = new $jit.ST({
'injectInto': 'infovis',
//set duration for the animation
duration: 800,
//set animation transition type
transition: $jit.Trans.Quart.easeInOut,
//set distance between node and its children
levelDistance: 50,
//set max levels to show. Useful when used with
//the request method for requesting trees of specific depth
levelsToShow: 2,
//set node and edge styles
//set overridable=true for styling individual
//nodes or edges
Node: {
height: 20,
width: 40,
//use a custom
//node rendering function
type: 'nodeline',
color:'#23A4FF',
lineWidth: 2,
align:"center",
overridable: true
},
Edge: {
type: 'bezier',
lineWidth: 2,
color:'#23A4FF',
overridable: true
},
//Add a request method for requesting on-demand json trees.
//This method gets called when a node
//is clicked and its subtree has a smaller depth
//than the one specified by the levelsToShow parameter.
//In that case a subtree is requested and is added to the dataset.
//This method is asynchronous, so you can make an Ajax request for that
//subtree and then handle it to the onComplete callback.
//Here we just use a client-side tree generator (the getTree function).
request: function(nodeId, level, onComplete) {
var ans = getTree(nodeId, level);
onComplete.onComplete(nodeId, ans);
},
onBeforeCompute: function(node){
Log.write("loading " + node.name);
},
onAfterCompute: function(){
Log.write("done");
},
//This method is called on DOM label creation.
//Use this method to add event handlers and styles to
//your node.
onCreateLabel: function(label, node){
label.id = node.id;
label.innerHTML = node.name;
label.onclick = function(){
st.onClick(node.id);
};
//set label styles
var style = label.style;
style.width = 40 + 'px';
style.height = 17 + 'px';
style.cursor = 'pointer';
style.color = '#fff';
//style.backgroundColor = '#1a1a1a';
style.fontSize = '0.8em';
style.textAlign= 'center';
style.textDecoration = 'underline';
style.paddingTop = '3px';
},
//This method is called right before plotting
//a node. It's useful for changing an individual node
//style properties before plotting it.
//The data properties prefixed with a dollar
//sign will override the global node style properties.
onBeforePlotNode: function(node){
//add some color to the nodes in the path between the
//root node and the selected node.
if (node.selected) {
node.data.$color = "#ff7";
}
else {
delete node.data.$color;
}
},
//This method is called right before plotting
//an edge. It's useful for changing an individual edge
//style properties before plotting it.
//Edge data proprties prefixed with a dollar sign will
//override the Edge global style properties.
onBeforePlotLine: function(adj){
if (adj.nodeFrom.selected && adj.nodeTo.selected) {
adj.data.$color = "#eed";
adj.data.$lineWidth = 3;
}
else {
delete adj.data.$color;
delete adj.data.$lineWidth;
}
}
});
//load json data
st.loadJSON(eval( '(' + json + ')' ));
//compute node positions and layout
st.compute();
//emulate a click on the root node.
st.onClick(st.root);
//end
//Add event handlers to switch spacetree orientation. - Which i do not want...
// function get(id) {
// return document.getElementById(id);
// };
// var top = get('r-top'),
// left = get('r-left'),
// bottom = get('r-bottom'),
// right = get('r-right');
// function changeHandler() {
// if(this.checked) {
// top.disabled = bottom.disabled = right.disabled = left.disabled = true;
// st.switchPosition(this.value, "animate", {
// onComplete: function(){
// top.disabled = bottom.disabled = right.disabled = left.disabled = false;
// }
// });
// }
// };
// top.onchange = left.onchange = bottom.onchange = right.onchange = changeHandler;
//end
}
You can drop in orientation:'top', shortly into the new $jit.ST function, ie:
var st = new $jit.ST({
//id of viz container element
injectInto: 'infovis',
//SET THE TREE TO VERTICAL
orientation:"top",
//set duration for the animation
duration: 800,
Source: https://groups.google.com/forum/#!searchin/javascript-information-visualization-toolkit/top/javascript-information-visualization-toolkit/MhXSXJUmaIk/V5JNwSe359gJ

webGL story sphere popups

I am trying to adapt the really cool looking WebGL Story Sphere, source code and css here. There's one big problem: once you click on a news article, the text of the article in the popup is always the same. I want to modify the code so that when you click on an article, the right text appears in the popup.
I'm working from a set of article texts that I specify in the code, e.g. var captions = ["good","better","best"]. Though the article titles and images populate correctly in the popup, I can't get the text to do so. Can you help me?? Here's what I've got:
// function code
var passvar = null; // failed attempt to store texts for later
function initialize() {
math = tdl.math;
fast = tdl.fast;
canvas = document.getElementById("canvas");
g_fpsTimer = new tdl.fps.FPSTimer();
hack();
canvas.addEventListener("mousedown", handleMouseDown, false);
canvas.addEventListener("mousemove", handleMouseMove, false);
canvas.addEventListener("mouseup", handleMouseUp, false);
// Create a canvas 2d for making textures with text.
g_canvas2d = document.createElement('canvas');
window.two2w = window.two2h = g_tilesize;
g_canvas2d.width = two2w;
g_canvas2d.height = two2h;
g_ctx2d = g_canvas2d.getContext("2d");
window.gl = wu.create3DContext(canvas);
if (g_debug) {
gl = wd.makeDebugContext(gl, undefined, LogGLCall);
}
//gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, gl.TRUE);
// Here is where I specify article titles, images, captions
// Titles and images populate the popup correctly, captions don't...
var titles = ["a","b","c"];
var captions = ["good","better","best"];
var images = ['imagesphere/assets/1.jpg',
'imagesphere/assets/bp/2.png',
'imagesphere/assets/bp/3.png'
];
var headlines = titles.concat( titles);
var blurbs = captions.concat( captions);
var tmpImages = [];
var tmpHeadlines = [];
var tmpCaptions = [];
// make a bunch of textures.
for (var ii = 0; ii < g_imagesDownGrid; ++ii) {
var textures = [];
for (var jj = 0; jj < g_imagesAcrossGrid; ++jj) {
var imgTexture = new ImgTexture();
textures.push(imgTexture);
if (tmpImages.length == 0) {
tmpImages = images.slice();
}
if (tmpHeadlines.length == 0) {
tmpHeadlines = headlines.slice();
}
if (tmpCaptions.length == 0) {
tmpCaptions = blurbs.slice();
}
var rando = math.randomInt(tmpImages.length);
var img = tmpImages.splice(rando, 1)[0];
var headline = tmpHeadlines.splice(rando, 1)[0];
var caption = tmpCaptions.splice(rando, 1)[0];
passvar = caption;
if (img.indexOf('videoplay.jpg') > -1){
window.vidtexture = imgTexture;
images = images.slice(1); // dont use that thumb again.
headlines = 'WebGL Brings Video To the Party as Well'
}
imgTexture.load(img, /* "[" + jj + "/" + ii + "]" + */ headline);
}
g_textures.push(textures);
}
// And here's where I try to put this in a popup, finally
// But passvar, the stored article text, never refreshes!!!
<div id="story" class="prettybox" style="display:none">
<img class="close" src="imagesphere/assets/close.png">
<div id="storyinner">
<input id = "mytext">
<script>document.getElementById("mytext").value = passvar;</script>
</div>
</div>
And here is my click handler code:
function sphereClick(e){
window.console && console.log('click!', e, e.timeStamp);
var selected = g_textures[sel.y][sel.x];
window.selected = selected;
animateGL('eyeRadius', glProp('eyeRadius'), 4, 500);
var wwidth = $(window).width(),
wheight = $(window).height(),
story = $('#story').width( ~~(wwidth / 7 * 4) ).height( ~~(wheight / 6 * 5) ),
width = story.width(),
height = story.height(),
miniwidth = 30;
story.detach()
.find('#storyinner').find('h3,img,caption').remove().end().end()
.show();
story.css({
left : e.pageX,
top : e.pageY,
marginLeft : - width / 2,
marginTop : - height / 2
}).appendTo($body); // we remove and put back on the DOM to reset it to the correct position.
$('style.anim.story').remove();
$('<style class="anim story">')
.text( '.storyopen #story { left : ' + (wwidth / 3 * 2) + 'px !important; top : ' + wheight / 2 + 'px !important; }' )
.appendTo($body);
$(selected.img).prependTo('#storyinner').parent();
$('<h3>').text(selected.msg.replace(/\(.*/,'')).prependTo('#storyinner');
$body.addClass('storyopen');
} // eo sphereClick()
There's a lot wrong here, but here's a start. It won't solve your problem, but it will help you avoid issues like this.
var passvar = null; is a global variable.
Your loop for (var ii = 0; ... sets that global variable to a new value on every iteration.
Later, you click something and the global variable passvar is never changed.
If you want to use this pattern, you need to set passvar from your click handler so it has the value that was clicked. Since you didn't actually post your click handlers, it's hard to advise more.
But this is also a bad pattern, functions take arguments for a good reason. Since you have to find your clicked item in the click handler anyway, why not pass it directly which does involve a shared global variable at all?
var handleMouseUp = function(event) {
var story = findClickedThing(event);
if (obj) {
showPopup(story.texture, story.caption);
}
}
Which brings me to this:
var titles = ["a","b","c"];
var captions = ["good","better","best"];
var images = ['imagesphere/assets/1.jpg',
'imagesphere/assets/bp/2.png',
'imagesphere/assets/bp/3.png'
];
When you have 3 arrays, all of the same length, each array describing a different property of an object, you are doing it wrong. What you want, is one array of objects instead.
var stories = [
{
title: "a",
caption: "good",
image: "imagesphere/assets/1.jpg"
}, {
title: "b",
caption: "better",
image: "imagesphere/assets/bp/2.jpg"
}, {
title: "c",
caption: "best",
image: "imagesphere/assets/bp/3.jpg"
},
];
console.log(stories[1].caption); // "better"
Now once you find the clicked object, you can just ask it what it's caption is. And you can pass the whole object to the popup maker. And no field is handled differently or passed around in a different manner, because you are not passing around the fields. You are passsing the entire object.

Categories

Resources