Pass variable to .animate property - animation

Bit of a n00b here.
I was trying to modify a hover function I'd found which positions and animates an image within a list item. Instead of giving .animate({top: an exact pixel value in the first instance, I wanted to pass it the variable imgHeight, which gets the height of the containing li, but I'm clearly doing something wrong. Any pointers?
var imgHeight = $('li').height();
$(function() {
$('ul.hover_block li').hover(function(){
$(this).find('img').animate({top:'imgHeight' + 'px'},{queue:false,duration:200});
}, function(){
$(this).find('img').animate({top:'0px'},{queue:false,duration:200});
});
});​

Try this instead: you had
{top: 'imgHeight' + 'px'}
Should be
{top: imgHeight + 'px'}
Full code:
var imgHeight = $('li').height();
$(function() {
$('ul.hover_block li').hover(function(){
$(this).find('img').animate({top:imgHeight + 'px'},{queue:false,duration:200});
}, function(){
$(this).find('img').animate({top:'0px'},{queue:false,duration:200});
});
});​

Related

How to capture the selection in a dc.js + crossfilter + d3.js chart?

perhaps the answer is very obvious and has nothing to do the libraries but with general javascript, JQuery or Ajax. I am very new to javascript and I was trying to implement a dashboard using flask as the backend.
Crossfilter and dc help me select ranges on the charts and see how that affects the whole dataset. If I add a:
<span class="filter"></span>
It will display the range above the chart
But that is a class "filter" inside a span object and not a variable or data that I can get inside the code. Below is what I use to display the chart (btw, the reset button does not appear at all)
<div class='span6' id='dc-close-chart'>
<h4>
close
</h4>
<p>range:
<span class="filter">
<a class="reset" href="javascript:closeChart.filterAll();dc.redrawAll();" style="display: none;">
reset
</a>
</span>
</p>
</div>
I would like to be able to do the following:
Be able to access that range and store it is a variable so I can access it and maybe post it using a submit button.
Be able to replace that label for an input textbox to modify the range and change the filter accordingly.
I've been looking around the crossfilter and dc.js forums but I didn't find anything relevant, what I want to do, is it even possible?
Below the JS code, can I create a variable that captures that?
var closeChart = dc.barChart("#dc-close-chart");
// set constants
var n_bins = 35;
d3.csv("/static/data2.csv", function (data) {
console.log(data);
data.forEach(function (d) {
d.close = d3.round(+d.close, 1);
});
// Run the data through crossfilter and load our 'facts'
var facts = crossfilter(data);
var all = facts.groupAll();
// count all the facts
dc.dataCount(".dc-data-count")
.dimension(facts)
.group(all);
// for Each chart numeric
var closeValue = facts.dimension(function (d) {
return d.close; // add the magnitude dimension
});
var closeValueGroupSum = closeValue.group()
.reduceSum(function (d) {
return d.close;
}); // sums
var closeValueGroupCount = closeValue.group()
.reduceCount(function (d) {
return d.close;
}) // counts
// extent
var closeExtent = d3.extent(data, function (d) {
return d.close;
});
// binwidth
var closebinWidth = (closeExtent[1] - closeExtent[0]) / n_bins;
//group
var closeGroup = closeValue.group(function (d) {
return Math.floor(d / closebinWidth) * closebinWidth;
});
// Setup the charts
// Magnitide Bar Graph Counted
closeChart.width(480)
.height(150)
.margins({
top: 10,
right: 10,
bottom: 20,
left: 40
})
.dimension(closeValue)
.group(closeGroup)
.transitionDuration(500)
.centerBar(true)
.gap(1) // 65 = norm
// .filter([3, 5])
.x(d3.scale.linear().domain(closeExtent).range([0, n_bins]))
.elasticY(true)
.xUnits(function () {
return n_bins;
})
.controlsUseVisibility(true)
.colors(['LimeGreen'])
.xAxis().tickFormat(function (v) {
return v;
});
// Render the Charts
dc.renderAll();
});
You can read the currently active filters using chart.filter() or chart.filters().
There isn't anything built in to parse filters from text, but if you figure out how to do that, you could apply the filter with
chart.replaceFilter([dc.filters.RangedFilter(min, max)])
RangedFilter docs.
replaceFilter docs.

nvd3 living chart Memory Leak [duplicate]

This question already has an answer here:
NVD3 - How to refresh the data function to product new data on click
(1 answer)
Closed 7 years ago.
I try to create a living line chart. I always show a fixed number of points adding a new one means removing an old one. To do this I use an interval timer to redraw the chart.
This works quite nice until I run the profiler and have a look at the memory consumption. This chart consumes a lot of memory and more and more for every step. I cannot see an obvious reason because the data is shift() out of the array after a new value is push() in.
var data = [{
"key" : "Long",
"values" : getData()
}];
var chart;
function redraw() {
nv.addGraph(function() {
var chart = nv.models.lineChart().margin({
left : 100
})
//Adjust chart margins to give the x-axis some breathing room.
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
//.transitionDuration(350) //how fast do you want the lines to transition?
.showLegend(true) //Show the legend, allowing users to turn on/off line series.
.showYAxis(true) //Show the y-axis
.showXAxis(true);
//Show the x-axis
chart.xAxis.tickFormat(function(d) {
return d3.time.format('%x')(new Date(d))
});
chart.yAxis.tickFormat(d3.format(',.1%'));
d3.select('#chart svg').datum(data)
//.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
}
function getData() {
var arr = [];
var theDate = new Date(2012, 01, 01, 0, 0, 0, 0);
for (var x = 0; x < 30; x++) {
arr.push({
x : new Date(theDate.getTime()),
y : Math.random() * 100
});
theDate.setDate(theDate.getDate() + 1);
}
return arr;
}
setInterval(function() {
var long = data[0].values;
var next = new Date(long[long.length - 1].x);
next.setDate(next.getDate() + 1)
long.shift();
long.push({
x : next.getTime(),
y : Math.random() * 100
});
redraw();
}, 1500);
What's wrong?
Thanks to #shabeer90 hint I found the solution. I just had to call the following method after the chart has been constructed.
function update() {
var data = getData();
// Update the SVG with the new data and call chart
chartData.datum(data).transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
};
And that's it!

How do I specify the velocity and threshold, using jQuery Hammer?

How do I specify the velocity and threshold, using jQuery Hammer?
$(window).load(function(){
$(function(){
var myElement = document.getElementById('myElement');
Hammer(myElement).on("swipeleft", function() {
console.log("drag left");
});
});
});
Don't know if you still need the answer, but your can change it like this:
var mc = new Hammer.Manager(myElement);
mc.add( new Hammer.Swipe({ velocity: 0.1, threshold: 0 }) );

viewportSize seems not to work with PhantomJS

Shouldn't the output from this PhantomJS script be 240x320 pixels? I'm getting a large, default-sized image. clipRect() would seem to render the correct size image, but I need the responsive content of the page to reflect the actual browser window size.
var page = require('webpage').create();
page.viewportSize = { width: 240, height: 320 };
page.open('http://cnn.com', function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
window.setTimeout(function () {
page.render('default.png');
phantom.exit();
}, 200);
}
});
This works!!
Found the snippet on the github page of the issue.It forces the 'body' element to the page viewportSize:
var width = 1024;
var height = 768;
var webpage = require('webpage');
page = webpage.create();
page.viewportSize = {width: width, height: height};
page.open('http://harness.io', function(status) {
console.log(status);
page.evaluate(function(w, h) {
document.body.style.width = w + "px";
document.body.style.height = h + "px";
}, width, height);
page.clipRect = {top: 0, left: 0, width: width, height: height};
page.render('/tmp/test.png');
phantom.exit();
});
This is a known issue but I found a workaround:
Load the page into an iframe of whatever size you like.
Render a screenshot clipped to the rectangle of the iframe.
There is code to do it in this repository: https://github.com/jbeuckm/Splasher
This seems to work in the Mac binary for 1.9.7:
page.set('viewportSize', {width: 320, height: 480});
In CasperJS, I dealt with this issue, used the above method(s), and ultimately found it was unnecessary (at least for me, in CasperJS) once I set the single viewport options via the casper.viewport() method.
I've posted my version below, so you can see how it could work with many urls at once.
// Requires node.js and casperjs (npm install casperjs)
var casper = require('casper').create();
var root_dir = 'screenshots/';
var links = [];
var root = 'http://localhost:8001/';
var DEBUG = false;
var opts = {top: 0, left: 0, 'width': 1280, 'height': 1024};
function getHrefs() {
// Taken wholesale from casperjs
// http://docs.casperjs.org/en/latest/quickstart.html
var links = document.querySelectorAll('.days li > a');
return Array.prototype.map.call(links, function(e) {
return e.getAttribute('href');
});
}
function captureLinks(links) {
casper.echo('= SCREEN CAPTURING LINKS ====');
casper.each(links, function(self, link) {
var filename = root_dir + link.replace('/index.html', '') + '.png';
casper.echo('Capturing... ' + filename);
// Relevant code...
this.viewport(opts.width, opts.height);
self.thenOpen(root + link, function() {
// slight delay for external libraries and init loading
this.wait(500, function(){
this.capture(filename, opts);
});
});
});
}
casper.start(root, function() {
links = links.concat(this.evaluate(getHrefs));
this.echo('= GETTING LINKS ====');
if(DEBUG) this.echo(links.join('\n'));
captureLinks(links);
});
casper.run();

Raphael JS : how to remove events?

I use the Raphael .mouseover() and .mouseout() events to highlight some elements in my SVG.
This works fine, but after I click on an element, I want it to stop highlighting.
In the Raphael documentation I found :
To unbind events use the same method names with “un” prefix, i.e. element.unclick(f);
but I can't get this to work and I also don't understand the 'f' parameter.
This doesn't work , but what does??
obj.click( function() {
this.unmouseover();
});
Ok, what you have to do is pass the handler function to the unmouseover request:
// Creates canvas 320 × 200 at 10, 50
var paper = Raphael(10, 50, 320, 200);
// Creates circle at x = 50, y = 40, with radius 10
var circle = paper.circle(50, 40, 10);
// Sets the fill attribute of the circle to red (#f00)
circle.attr("fill", "#f00");
// Sets the stroke attribute of the circle to white
circle.attr("stroke", "#fff");
var mouseover = function (event) {
this.attr({fill: "yellow"});
}
var mouseout = function (event) {
this.attr({fill: "red"});
}
circle.hover(mouseover, mouseout);
circle.click(function (event) {
this.attr({fill: "blue"});
this.unmouseover(mouseover);
this.unmouseout(mouseout);
});
http://jsfiddle.net/GexHj/1/
That's what f is about. You can also use unhover():
circle.click(function (event) {
this.attr({fill: "blue"});
this.unhover(mouseover, mouseout);
});
http://jsfiddle.net/GexHj/2/

Resources