mootools
It's often interesting to think about where on a given element, whether it be the page, an image, or a static DIV, your users are clicking. With that curiosity in mind, I've created HeatMap: a MooTools class that allows you to detect, load, save, and display spots on a given area where a user has clicked.
考虑给定元素在用户单击的位置上是有趣的,无论是页面,图像还是静态DIV。 考虑到这种好奇心,我创建了HeatMap:一个MooTools类,使用该类可以检测,加载,保存和显示用户单击的给定区域上的斑点。
CSS (The CSS)
There's really only one CSS declaration you'll need to make with HeatMap, and that's the CSS class that represents how a spot should look. A sample spot CSS class could look like:
实际上,您只需要使用HeatMap进行一个CSS声明,这就是表示斑点外观CSS类。 一个示例CSS类示例如下所示:
.heatmap-spot {
width:6px;
height:6px;
margin-top:-3px;
margin-left:-3px;
-webkit-border-radius:4px;
-moz-border-radius:4px;
background:#fff;
position:absolute; /* important! */
z-index:200;
}
HeatMap was created to allow spot styling to look however you'd like. Note that you'll want to add negative margins to the spot depending on how large you create the spot.
HeatMap的创建是为了使点样式看起来像您想要的那样。 请注意,您将要根据创建斑点的大小向该斑点添加负边距。
MooTools JavaScript (The MooTools JavaScript)
The class is relatively compact but grew larger than I had expected. HeatMap allows for easy loading and saving of spots with minimal code. Here's the complete class:
该课程相对紧凑,但比我预期的要大。 HeatMap可以使用最少的代码轻松加载和保存斑点。 这是完整的课程:
var HeatMap = new Class({
options: {
event: 'click',
load: {
// request settings here
},
method: 'get',
save: {
// request settings here
},
spotClass: 'heatmap-spot',
zone: ''/*,
onClick: $empty,
onSpot: $empty
*/
},
Implements: [Options,Events],
initialize: function(element,options) {
this.element = document.id(element).setStyle('position','relative');
this.setOptions(options);
this.newClicks = [];
this.oldClicks = [];
this.attachEvents();
},
attachEvents: function() {
var self = this;
this.clickEvent = function(e) {
var obj = self.getRelativePosition(e.page.x,e.page.y);
obj.spot = self.createSpot(obj.x,obj.y);
self.newClicks.push(obj);
};
this.element.addEvent(this.options.event,this.clickEvent);
},
detachEvents: function() {
this.element.removeEvent(this.options.event,this.clickEvent);
},
getRelativePosition: function(x,y) {
var position = this.element.getPosition();
return { x: x - position.x, y: y - position.y };
},
load: function() {
if(!this.loadRequest) this.loadRequest = new Request.JSON(this.options.load);
if(!this.options.load.onSuccess && !this.loadSuccess) {
this.loadSuccess = function(json) {
json.each(function(click,i) {
json[i].spot = this.createSpot(click.x,click.y);
this.oldClicks.push(json[i]);
},this);
}.bind(this);
this.loadRequest.addEvent('success',this.loadSuccess);
}
this.loadRequest[this.options.method]({
load: 1,
zone: this.options.zone
});
return this;
},
save: function(data) {
if(!this.sendRequest) this.sendRequest = new Request.JSON(this.options.save);
if(this.newClicks.length) {
this.sendRequest.addEvent('success',function() {
this.newClicks.each(function(click) {
this.oldClicks.push(this.createSpot({ x: click.x, y:click.y }));
},this);
this.newClicks = [];
}.bind(this));
this.sendRequest[this.options.method]({
save: 1,
zone: this.options.zone,
data: this.newClicks
});
}
return this;
},
createSpot: function(x,y) {
var spot = new Element('div',{
'class': this.options.spotClass,
styles: {
top: y.toInt(),
left: x.toInt()
}
}).inject(this.element);
this.fireEvent('spot',[spot,x,y]);
return spot;
}
});
Arguments for HeatMap include:
HeatMap的参数包括:
element: the element with which to listen for clicks on
element:用于监听点击的元素
options: options for the class instance
options:类实例的选项
Options for HeatMap include:
HeatMap的选项包括:
event: (string, defaults to event) the event to listen for -- defaults to click
event :( 字符串,默认为event)要监听的事件-默认为click
load: (object, defaults to {}) the Request.JSON options object for loading spots
load :( 对象,默认为{})用于加载点的Request.JSON选项对象
method: (string, defaults to "get") the Request.JSON request type
方法:( 字符串,默认为“ get”) Request.JSON请求类型
save: (object, defaults to {}) the Request.JSON options object for saving spots
保存:( 对象,默认为{})用于保存位置的Request.JSON选项对象
spotClass: (string, defaults to 'heatmap-spot') the CSS class for styling a spot
spotClass :( 字符串,默认为“ heatmap-spot”)用于设置点样式CSS类
zone: (string, defaults to '') the "zone" by which the click will be saved under; especially important if more than one spot is one the page.
zone :( 字符串,默认为“”)单击将保存到的“区域”; 如果一页以上有多个斑点,则尤其重要。
Events for HeatMap include:
HeatMap的事件包括:
onSpot: fires when a spot is created.
onSpot:创建专色时触发。
A relatively simple class. The class could have more complexity but I've chosen to keep it simple for iteration one.
一个相对简单的类。 该类可能会有更多的复杂性,但我选择对第一个迭代保持简单。
HeatMap的用法 (HeatMap Usage)
Using HeatMap is as simple as this:
使用HeatMap就是这样简单:
/* usage */
window.addEvent('domready',function() {
map = new HeatMap('ricci-map',{
zone: 'cricci',
save: { url: 'heat-map.php' },
load: { url: 'heat-map.php' },
onSpot: function(spot) {
spot.setStyle('opacity',0).fade(1);
}
});
document.id('loader').addEvent('click',function() {
map.load();
});
document.id('saver').addEvent('click',function() {
map.save();
});
});
Much simpler than you had probably imagined! I'd recommend using click
as the event -- using other types of events could be confusing to users and could result in massive amounts of data for mouseenter
events.
比您想像的要简单得多! 我建议将click
作为事件使用-使用其他类型的事件可能会使用户感到困惑,并可能导致mouseenter
事件的大量数据。
MySQL表 (The MySQL Table)
My MySQL table looks as follows:
我MySQL表如下所示:
CREATE TABLE `example_heatmap` (
`click_id` mediumint(6) NOT NULL auto_increment,
`zone` varchar(60) NOT NULL default '',
`x` smallint(5) NOT NULL default '0',
`y` smallint(5) NOT NULL default '0',
`date_clicked` datetime NOT NULL,
PRIMARY KEY (`click_id`)
) ENGINE=MyISAM AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;
How you choose to set up the SQL side of this is entirely up to you.
如何选择设置SQL方面完全取决于您。
PHP脚本 (The PHP Script )
A few thing I'd like to point out about the server-side handling of HeatMap:
我想指出一些有关HeatMap服务器端处理的信息:
- You can use any server-side language to facilitate the loading of saving of spots -- I simply used PHP because it's what I'm most familiar with. 您可以使用任何服务器端语言来方便加载位置信息-我只是使用PHP,因为这是我最熟悉的语言。
- Save your complaints about my usage of PHP's native mysql functions and the lack of validation -- my focus with this post is the JavaScript class. 不用担心我对PHP原生mysql函数的使用以及缺乏验证的问题,我的重点是JavaScript类。
Without further adieu, here's a PHP solution for saving and loading spots:
无需其他条件,这是一个用于保存和加载点PHP解决方案:
/* load */
if(isset($_GET['load'])) {
/* vars */
$spots = array();
/* connect to the db */
$connection = mysql_connect('localhost','dbuser','dbpass');
mysql_select_db('dbname',$connection);
/* get spots */
$query = 'SELECT * FROM example_heatmap WHERE zone = \''.mysql_escape_string($_GET['zone']).'\' LIMIT 2000';
$result = mysql_query($query,$connection);
while($record = mysql_fetch_assoc($result)) {
$spots[] = $record;
}
/* close db connection */
mysql_close($connection);
/* return result */
$json = json_encode($spots);
echo $json;
die();
}
/* save */
elseif(isset($_GET['save']) && isset($_GET['data']) && count($_GET['data'])) {
/* vars */
$query = 'INSERT INTO example_heatmap (zone,x,y,date_clicked) VALUES ';
$queryRecords = array();
$records = 0;
/* connect to the db */
$connection = mysql_connect('localhost','dbuser','dbpass');
mysql_select_db('dbname',$connection);
/* save! */
foreach($_GET['data'] as $data) {
$queryRecords[] = '(\''.mysql_escape_string($_GET['zone']).'\','.mysql_escape_string($data['x']).','.mysql_escape_string($data['y']).',NOW())';
$records++;
}
/* execute query, close */
$query.= implode(',',$queryRecords);
mysql_query($query,$connection);
mysql_close($connection);
/* return result */
die(count($records));
}
I prefer to use one script for both the saving and loading of spots -- using one script cuts down on the number of files you need and the logic to handle multiple functionality isn't difficult to organize within that one file.
我更喜欢使用一个脚本来保存和加载位置-使用一个脚本可以减少所需的文件数量,并且在一个文件内组织多种功能的逻辑并不难。
带上热量! (Bring the Heat!)
MooTools HeatMap is something I find incredibly fun. You could use HeatMap on an image, a static DIV, or the entire body. If you don't want the user to see spots and simply want to track their clicks, you could hide spots and periodically save clicks. Have fun with this class and let me know if you have suggestions!
我发现MooTools HeatMap非常有趣。 您可以在图像,静态DIV或整个身体上使用HeatMap。 如果您不希望用户看到斑点,而只想跟踪他们的点击,则可以隐藏斑点并定期保存点击。 玩得开心,让我知道是否有建议!
mootools