I am using DC chart range filter. I want to handle mouse out event on range filter, so I can handle filter on mouse-out. I had used filter and post-redraw but when I use this there are multiple time event fire on single drag on range chart. I need only the last change event and I think a mouse out or mouse up event would be helpful. Can any one help me with how to use mouse up/mouse out event on range Chart?
chart.on('postRender', function() {
chart.select('.brush').on("mouseover", function() {
console.log('mouseover');
});
chart.select('.brush').on("mouseout", function() {
console.log('mouseout');
});
chart.select('.brush').on("mouseup", function() {
console.log('mouseup')
});
chart.select('.brush').on("click", function() {
console.log('click')
});
});
Working snippet below:
var data = [{
date: "2011-11-21",
total: 90
}, {
date: "2011-11-22",
total: 90
}, {
date: "2011-11-23",
total: 90
}, {
date: "2011-11-24",
total: 200
}, {
date: "2011-11-25",
total: 200
}];
var cf = crossfilter(data);
var timeDimension = cf.dimension(function(d) {
return new Date(d.date);
});
var totalGroup = timeDimension.group().reduceSum(function(d) {
return d.total;
});
var chart = dc.lineChart("#chart")
.width(400)
.height(200)
.x(d3.time.scale().domain(d3.extent(data, function(d) {
return new Date(d.date);
})))
.dimension(timeDimension)
.group(totalGroup)
.renderArea(true)
.brushOn(true);
chart.xAxis().ticks(4);
function caught(eventName) {
document.getElementById(eventName).className = 'bold';
setTimeout(function() {
document.getElementById(eventName).className = '';
}, 750);
}
chart.on('postRender', function() {
chart.select('.brush').on("mouseover", function() {
console.log('mouseover');
caught('mouseover');
});
chart.select('.brush').on("mouseout", function() {
console.log('mouseout');
caught('mouseout');
});
chart.select('.brush').on("mouseup", function() {
console.log('mouseup')
caught('mouseup');;
});
chart.select('.brush').on("click", function() {
console.log('click')
caught('click');;
});
});
chart.render();
<link href="https://cdnjs.cloudflare.com/ajax/libs/dc/1.7.3/dc.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.2.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.11/crossfilter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dc/1.7.3/dc.js"></script>
<style>
.bold {
font-weight: bold;
}
</style>
<div id="chart"></div>
<div id="mouseout">mouseout</div>
<div id="mouseover">mouseover</div>
<div id="mouseup">mouseup</div>
<div id="click">click</div>
Related
I have a lot of problem to upload multiple images using AJAX. I write this code:
HTML
<form id="upload" method="post" enctype="multipart/form-data">
<div id="drop" class="drop-area">
<div class="drop-area-label">
Drop image here
</div>
<input type="file" name="file" id="file" multiple/>
</div>
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
jQuery/AJAX
$(document).on("change", "input[name^='file']", function(e){
e.preventDefault();
var This = this,
display = $("#uploads");
// list all file data
$.each(This.files, function(i, obj){
// for each image run script asynchronous
(function(i) {
// get data from input file
var file = This.files[i],
name = file.name,
size = file.size,
type = file.type,
lastModified = file.lastModified,
lastModifiedDate = file.lastModifiedDate,
webkitRelativePath = file.webkitRelativePath,
slice = file.slice,
i = i;
// DEBUG
/*
var acc = []
$.each(file, function(index, value) {
acc.push(index + ": " + value);
});
alert(JSON.stringify(acc));
*/
$.ajax({
url:'/ajax/upload.php',
contentType: "multipart/form-data",
data:{
"image":
{
"name":name,
"size":size,
"type":type,
"lastModified":lastModified,
"lastModifiedDate":lastModifiedDate,
"webkitRelativePath":webkitRelativePath,
//"slice":slice,
}
},
type: "POST",
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
// Check if upload property exists
if(myXhr.upload)
{
// For handling the progress of the upload
myXhr.upload.addEventListener("progress",progressHandlingFunction, false);
}
return myXhr;
},
cache: false,
success : function(data){
// load ajax data
$("#listTable").append(data);
}
});
// display progress
function progressHandlingFunction(e){
if(e.lengthComputable){
var perc = Math.round((e.loaded / e.total)*100);
perc = ( (perc >= 100) ? 100 : ( (perc <= 0) ? 0 : 0 ) );
$("#progress"+i+" > div")
.attr({"aria-valuenow":perc})
.css("width", perc+"%");
}
}
// display list of files
display.append('<li>'+name+'</li><div class="progress" id="progress'+i+'">'
+'<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">'
+'</div></div>');
})(i);
});
});
I've tried a various versions and I never succeed to send multiple data through ajax. I have tried in this way what you see above, and now I get only POST informations. I understand why i get POST but I need to send FILES information and I do not know where I'm wrong.
I not work the first time with ajax and often use it for most projects but I have never used to send multiple files and that bothering me now.
Thanks!
Try utilizing json to upload , process file object
html
<div id="drop" class="drop-area ui-widget-header">
<div class="drop-area-label">Drop image here</div>
</div>
<br />
<form id="upload">
<input type="file" name="file" id="file" multiple="true" accepts="image/*" />
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
css
#uploads {
display:block;
position:relative;
}
#uploads li {
list-style:none;
}
#drop {
width: 90%;
height: 100px;
padding: 0.5em;
float: left;
margin: 10px;
border: 8px dotted grey;
}
#drop.hover {
border: 8px dotted green;
}
#drop.err {
border: 8px dotted orangered;
}
js
var display = $("#uploads"); // cache `#uploads`, `this` at `$.ajax()`
var droppable = $("#drop")[0]; // cache `#drop` selector
$.ajaxSetup({
context: display,
contentType: "application/json",
dataType: "json",
beforeSend: function (jqxhr, settings) {
// pre-process `file`
var file = JSON.parse(
decodeURIComponent(settings.data.split(/=/)[1])
);
// add `progress` element for each `file`
var progress = $("<progress />", {
"class": "file-" + (!!$("progress").length
? $("progress").length
: "0"),
"min": 0,
"max": 0,
"value": 0,
"data-name": file.name
});
this.append(progress, file.name + "<br />");
jqxhr.name = progress.attr("class");
}
});
var processFiles = function processFiles(event) {
event.preventDefault();
// process `input[type=file]`, `droppable` `file`
var files = event.target.files || event.dataTransfer.files;
var images = $.map(files, function (file, i) {
var reader = new FileReader();
var dfd = new $.Deferred();
reader.onload = function (e) {
dfd.resolveWith(file, [e.target.result])
};
reader.readAsDataURL(new Blob([file], {
"type": file.type
}));
return dfd.then(function (data) {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: {
"file": JSON.stringify({
"file": data,
"name": this.name,
"size": this.size,
"type": this.type
})
},
xhr: function () {
// do `progress` event stuff
var uploads = this.context;
var progress = this.context.find("progress:last");
var xhrUpload = $.ajaxSettings.xhr();
if (xhrUpload.upload) {
xhrUpload.upload.onprogress = function (evt) {
progress.attr({
"max": evt.total,
"value": evt.loaded
})
};
xhrUpload.upload.onloadend = function (evt) {
var progressData = progress.eq(-1);
console.log(progressData.data("name")
+ " upload complete...");
var img = new Image;
$(img).addClass(progressData.eq(-1)
.attr("class"));
img.onload = function () {
if (this.complete) {
console.log(
progressData.data("name")
+ " preview loading..."
);
};
};
uploads.append("<br /><li>", img, "</li><br />");
};
}
return xhrUpload;
}
})
.then(function (data, textStatus, jqxhr) {
console.log(data)
this.find("img[class=" + jqxhr.name + "]")
.attr("src", data.file)
.before("<span>" + data.name + "</span><br />");
return data
}, function (jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
return errorThrown
});
})
});
$.when.apply(display, images).then(function () {
var result = $.makeArray(arguments);
console.log(result.length, "uploads complete");
}, function err(jqxhr, textStatus, errorThrown) {
console.log(jqxhr, textStatus, errorThrown)
})
};
$(document)
.on("change", "input[name^=file]", processFiles);
// process `droppable` events
droppable.ondragover = function () {
$(this).addClass("hover");
return false;
};
droppable.ondragend = function () {
$(this).removeClass("hover")
return false;
};
droppable.ondrop = function (e) {
$(this).removeClass("hover");
var image = Array.prototype.slice.call(e.dataTransfer.files)
.every(function (img, i) {
return /^image/.test(img.type)
});
e.preventDefault();
// if `file`, file type `image` , process `file`
if (!!e.dataTransfer.files.length && image) {
$(this).find(".drop-area-label")
.css("color", "blue")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
}).dequeue("msg");
return "File dropped, processing file upload...";
});
processFiles(e);
} else {
// if dropped `file` _not_ `image`
$(this)
.removeClass("hover")
.addClass("err")
.find(".drop-area-label")
.css("color", "darkred")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
.parent("#drop").removeClass("err")
}).dequeue("msg");
return "Please drop image file...";
});
};
};
php
<?php
if (isset($_POST["file"])) {
// do php stuff
// call `json_encode` on `file` object
$file = json_encode($_POST["file"]);
// return `file` as `json` string
echo $file;
};
jsfiddle http://jsfiddle.net/guest271314/0hm09yqo/
How to delay the scroll down for few seconds?
My Code:
<script type="text/javascript">
$(function(){
$("#tmp_image-37113").click (function() {
$('#section--41340').show(150);
$('html, body').animate ({
scrollTop: $("#section--41340").offset().top
}, 2000);
return false;
});
});
</script>
I am building a pie-chart with nvd3 and cannot figure out how to make the title dynamic or at least to run a callback when a user hovers over a slice of the pie.
This is the relevant part of my code:
nv.addGraph(function () {
let chart : any = nv.models.pieChart()
.x(function (d : any) {
return d.label;
})
.y(function (d : any) {
return d.value;
})
.showLabels(false)
.labelThreshold(.05) //Configure the minimum slice size for labels to show up
.labelType("percent") //Configure what type of data to show in the label. Can be "key", "value" or "percent"
.donut(true) //Turn on Donut mode. Makes pie chart look tasty!
.donutRatio(0.6) //Configure how big you want the donut hole size to be.
.showLegend(false)
.color(function (d : any) {
return d.data.color;
})
.width(300)
.height(300)
.title("Hello");
//.on("mouseover", function(d: any) { console.log(d); });
d3.select("#chart svg")
.datum(exampleData())
.transition().duration(350)
.call(chart);
return chart;
});
The chart works exactly as intended otherwise.
This is a codepen with the chart. For some reason the color does not work but in my own site it works.
You can use dispatch method of NVD3 library for event subscribing and of course, you can use any native d3 methods, for example d3.select. Just add this to your code:
chart.pie.dispatch.on('elementMouseover', function(e) {
d3.select('.nv-pie-title').text(e.label);
});
chart.pie.dispatch.on('elementMouseout', function(e) {
d3.select('.nv-pie-title').text("Hello");
});
Check working demo in the hidden snippet below:
nv.addGraph(function() {
let chart = nv.models.pieChart()
.x(function(d) {
return d.label;
})
.y(function(d) {
return d.value;
})
.showLabels(false)
.labelThreshold(.05) //Configure the minimum slice size for labels to show up
.labelType("percent") //Configure what type of data to show in the label. Can be "key", "value" or "percent"
.donut(true) //Turn on Donut mode. Makes pie chart look tasty!
.donutRatio(0.6) //Configure how big you want the donut hole size to be.
.showLegend(false)
.color(function(d) {
return d.data.color;
})
.width(300)
.height(300)
.title("Hello");
//.on("mouseover", function(d: any) { console.log(d); });
chart.pie.dispatch.on('elementMouseover', function(e) {
d3.select('.nv-pie-title').text(e.label);
});
chart.pie.dispatch.on('elementMouseout', function(e) {
d3.select('.nv-pie-title').text("Hello");
});
d3.select("#chart svg")
.datum(exampleData())
.transition().duration(350)
.call(chart);
return chart;
});
function exampleData() {
return [{
label: "timeout",
value: "14.2",
data: {
"color": "#f00"
}
}, {
label: "uncontacted",
value: "78.8",
data: {
"color": "#999999"
}
}, {
label: "refused",
value: "6.9",
data: {
"color": "#FFFFFF"
}
}];
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.6/nv.d3.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.7.0/nv.d3.min.js"></script>
<div id="chart">
<svg style="height: 300px; margin: -20px 0;"></svg>
</div>
Im trying to load this column chart with external data in Json format from a file
I have a jsfiddle with what i have so far.
Thanks for any help.
http://jsfiddle.net/t9n4d8z4/1/
$(document).ready(function() {
var dataPoints = [];
$.getJSON("https://api.myjson.com/bins/1kfs1", function(result) {
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({
label: result[i].label,
y: parseInt(result[i].y)
});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
type: "column",
dataPoints: result
}]
});
chart.render();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
json format was not handled properly.
Here is the working fiddle : http://jsfiddle.net/canvasjs/t9n4d8z4/3/
$(document).ready(function() {
var dataPoints = [];
$.getJSON("https://api.myjson.com/bins/1kfs1", function(result) {
for (var i = 0; i <= result.dataPoints.length - 1; i++) {
dataPoints.push({
label: result.dataPoints[i].label,
y: parseInt(result.dataPoints[i].y)
});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
type: "column",
dataPoints: dataPoints
}]
});
chart.render();
});
});
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
I am using J Vector Map (http://jvectormap.com/documentation/javascript-api/) to create a map of the United States.
What I want to be able to do is have a button for each state that you can click on and have the corresponding region in the map be selected (or unselected, if it already was selected). I am trying to use map.setSelectedRegion for this, but I can't get any of the code to work. Currently trying map.setSelectedRegion("US-CA") to no avail.
Any ideas on what to do?
Thanks!
There seem to be a lot of request for linking links with jvectormap.
I've put together a jsfiddle here: http://jsfiddle.net/3xZ28/117/
HTML
<ul id="countries">
<li>Romania</li>
<li>Australia</li>
</ul>
<div id="world-map" style="width: 600px; height: 400px"></div>
JS
var wrld = {
map: 'world_mill_en',
regionStyle: {
hover: {
"fill": 'red'
}
}
};
function findRegion(robj, rname) {
var code = '';
$.each(robj, function (key) {
if ( unescape(encodeURIComponent(robj[key].config.name)) === unescape(encodeURIComponent(rname)) ) {
code = key;
};
});
return code;
};
$(document).ready(function () {
$('#world-map').vectorMap(wrld);
var mapObj = $('#world-map').vectorMap('get', 'mapObject');
$('#countries').on('mouseover mouseout', 'a:first-child', function (event) {
// event.preventDefault();
var elem = event.target,
evtype = event.type,
cntrycode = findRegion(mapObj.regions, $(elem).text());
if (evtype === 'mouseover') {
mapObj.regions[cntrycode].element.setHovered(true);
} else {
mapObj.regions[cntrycode].element.setHovered(false);
};
});
});
Once you've set the handle
var mapObject = $('#your_map_div_id').vectorMap('get', 'mapObject');
Just use the built in function setSelectedRegions (mind the "s"):
mapObject.setSelectedRegions(your_region_code); //to set
mapObject.setSelectedRegions({your_region_code:false}); //to unset
If it still doesn't work, post your code, maybe it's something else.
This code is outdated, below is updated version of the code, according jvectormap latest API. Here is demo snippet:
<!DOCTYPE html>
<html>
<head>
<title>jVectorMap demo</title>
<link rel="stylesheet" href="jqvmap.min.css" type="text/css" media="screen"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="jquery.vmap.min.js"></script>
<script src="jquery.vmap.world.js"></script>
<script>
jQuery(document).ready(function () {
$('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#2f95c9',
color: '#ffffff',
hoverOpacity: 0.7,
selectedColor: '#666666',
enableZoom: true,
showTooltip: true,
scaleColors: ['#C8EEFF', '#006491'],
normalizeFunction: 'polynomial',
regionsSelectableOne: false,
regionsSelectable: false,
series: {
regions: [{
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'
}]
}
});
var mapObj = $('#vmap').data('mapObject');
$('#countries').on('mouseover mouseout', 'a:first-child', function (event) {
// event.preventDefault();
var elem = event.target,
evtype = event.type;
if (evtype === 'mouseover') {
mapObj.select($(elem).attr('id'));
} else {
mapObj.deselect($(elem).attr('id'));
};
});
});
</script>
</head>
<body>
<ul id="countries">
<li><a id="RO" href="">Romania</a></li>
<li><a id="AU" href="">Australia</a></li>
</ul>
<div id="vmap" style="width: 100vw; height: 100vh;"></div>
</body>
</html>