Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,6 @@
</div>
</div>
<a href="/" id="link5" data-ahoy-skip="true"><span>Link 5</span></a>
<a href="/" id="link6" data-foo="bar"><span>Link 6</span></a>
</body>
</html>
29 changes: 27 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -267,21 +267,46 @@ function presence(str) {
function cleanObject(obj) {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (obj[key] === null) {
const value = obj[key];

if (value === null || isLiteralObject(value) && isEmpty(value)) {
delete obj[key];
}
}
}
return obj;
}

function isLiteralObject(obj) {
return (!!obj) && (obj.constructor === Object);
}

function getDatasetInKebabCase(element) {
const datasetInKebabCase = {};

for (const attrName in element.attributes) {
if (Object.prototype.hasOwnProperty.call(element.attributes, attrName)) {
const attr = element.attributes[attrName];

if (attr.name.startsWith('data-')) {
const keyWithoutDataPrefix = attr.name.replace('data-', '');

datasetInKebabCase[keyWithoutDataPrefix] = attr.value;
}
}
}

return datasetInKebabCase;
}

function eventProperties() {
return cleanObject({
tag: this.tagName.toLowerCase(),
id: presence(this.id),
"class": presence(this.className),
page: page(),
section: getClosest(this, "data-section")
section: getClosest(this, "data-section"),
data: getDatasetInKebabCase(this)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
data: getDatasetInKebabCase(this)
data: this.dataset

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

seams to be available accross browsers:
https://caniuse.com/?search=dataset

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there!

this.dataset returns camelCase, but I'm returning them in kebab-case, so that the event properties reflect exactly how the element had them written, minus the data prefix. e.g.

<div data-foo-bar="baz"></div>

Would be:

properties: {
  data: {
    "foo-bar": "baz"
  }
}

});
}

Expand Down