Extend jQuery attribute starting with
Data attributes. Grab string at the end of data-
by Nirvanachain
HTML
<a href="#" title="Click Here"
data-wt-WT.AC="Hero Feature click"
data-wt-WT.cg_n="Engagement Events"
data-wt-WT.cg_s="Body Feature Position Click' + document.title"
data-wt-DCS.dcsuri="FeaturePositionClick"
data-wt-WT.dl="99" data-wt-meow="5"
data-rel="something else"/>Tag Me!</a><br />
<a href="#" data-rel="woof">Don't Tag Me!</a><br />
<a href="#" title="Click Here" data-wt-WT.AC="Jon Testing 2" data-wt-WT.cg_n="foo" data-wt-WT.cg_s="bar' + $('this).innerText()" data-wt-DCS.dcsuri="meow" data-wt-WT.dl="42" data-rel="something else"/>Tag Me Too!</a>
<div id="result"></div>
CSS
#result {
margin-top:10px;
height:150px;
font-size:.8em;
}
body {
font-family:verdana, arial, sans-serif; font-size:.8em;
}
JavaScript
//extend jQuery for new selector for finding element with attribute name that starts with
//usage $('element:attrStart(attributeprefix)');
//example $(a:attrStart(data-wt)')
$.extend($.expr[':'], {
attrStart: function (el, i, props) {
var hasAttribute = false;
$.each(el.attributes, function (i, attr) {
if (attr.name.indexOf(props[3]) !== -1) {
hasAttribute = true;
return false; // to halt the iteration
}
});
return hasAttribute;
}
});
//select any element that has attribute starting with data-wt and add click event
//key will always be lower case... does this matter? I don't know
$('a:attrStart(data-wt)').click(function () {
var el = $(this),
wtTrackElements = '',
output;
$.each(el.data(), function (key, value) {
if (key.indexOf('wt') != -1) {
wtTrackElements += '"' + key.replace('wt', '') + '", ' + value + ', ';
}
});
output = 'dcsMultiTrack(' + wtTrackElements + ');'
$('#result').append(output + '<br /><br />'); //Print results to the page.
return false;
});