Reputation: 53866
I plan to add some basic user usage of multiple html pages. To achieve this I want to introduce as little code changes to existing pages as possible. Here is my approach :
Import .js
file that contains operations to add listeners to the page and when an event is fired then invoke a function :
<title>myTitle</title>
<input id="click" type="submit" value="click"/>
<input id="test" type="textbox" value="test"/>
<a id="href">href</a>
$('a').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
$('input').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
function sendData(dataToSend) {
console.log('Sending data \n '+dataToSend)
}
for now sendData is just a dummy function, but I plan to modify this to send an ajax request to server endpoint with the dataToSend value.
Is there an alternative method of monitoring what the user clicks instead of coding a
tags and input
tags ? There may be other input types that I'm not aware of that may get clicked that will not be tracked ?
fiddle :
http://jsfiddle.net/g2Rxc/167/
Upvotes: 0
Views: 422
Reputation: 2285
You just need to plan what do you want to track, before write the code. By doing that you are going to find which elements and events you really want to track. With that in mind you will write something like:
$('everyElementSeparatedByComma').on('everyEventSeparatedByComma', function(){
...
});
A real example:
$('a, input, textarea, form').on('click, change, keypress, submit', function(){
...
});
Upvotes: 0
Reputation: 35670
Because click
events may be added after you've imported your listener code, you'll want to use event delegation on the document
element.
Since you're running jQuery v 1.6, you'll need to use the delegate
method:
$(document).delegate('*', 'click', function(e) {
var linker = $(this).attr('id'),
title = $(document).find("title").text(),
url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
return false;
});
Later versions of jQuery handle event delegation using the on
method:
$(document).on('click', '*', function(e) {
var linker = $(this).attr('id'),
title = $(document).find("title").text(),
url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
return false;
});
Upvotes: 1
Reputation: 32354
I see that your click functions do the same thing so you can nest all the elements in a single click event:
$('a,input,textare,..,..').click(function(e) {
var linker = $(this).attr('id');
var title = $(document).find("title").text();
var url = window.location.href;
sendData(linker+'\n'+title+'\n'+url);
});
Upvotes: 0