ahoy.js icon indicating copy to clipboard operation
ahoy.js copied to clipboard

[Idea] Remove TailwindCSS classes from "class" attribute in ahoy.js

Open hjhart opened this issue 3 years ago • 1 comments

Hi there! Love using ahoy, I think it's a great product. Thanks to all who has worked on it.

I did a quick search through the issues but wasn't able to come up with any relevant questions, so here goes:

Using tailwind CSS adds a lot of classes to our button elements. When I click on a button this is the tracking JSON that gets pushed to ahoy.

[
   {
      "name":"$click",
      "properties":{
         "tag":"a",
         "class":"appearance-none cursor-pointer flex focus:border-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 font-sans font-medium rounded-full transition ease-out duration-300  text-2xl justify-center px-4 mt-6 mr-6 md:mt-8 md:mr-8 custom-class",
         "page":"/redacted/redacted",
         "text":"close",
         "href":"http://redacted.com"
      },
      "time":1643737795.999,
      "id":"fd57268c-34f8-4726-a00a-f4d96d320df6",
      "js":true
   }
]

Specifically what I am interested in is removing a lot of the cruft that comes along with the class attribute.

I wonder if we should give people the option to filter out certain classes that provide no value to tracking? In this case I'd want to filter out every class except custom-class at the end.

So, desired tracking output would be:

[
   {
      "name":"$click",
      "properties":{
         "tag":"a",
         "class":"custom-class",
         "page":"/redacted/redacted",
         "text":"close",
         "href":"http://redacted.com"
      },
      "time":1643737795.999,
      "id":"fd57268c-34f8-4726-a00a-f4d96d320df6",
      "js":true
   }
]

Thanks in advance!

hjhart avatar Feb 01 '22 17:02 hjhart

I think you meant to create this issue on https://github.com/ankane/ahoy.js.

In any case, you can already do this yourself - you can send whatever data you want to ahoy.track.

For example, here is a function for your use case, based on the original ahoy.trackClicks function.

function trackClicksAndCleanClassnames(selector) {
  let trackableClassnames = ['custom-class'];

  if (selector === undefined) {
    throw new Error("Missing selector");
  }
  onEvent("click", selector, function (e) {
    let properties = eventProperties.call(this, e);
    properties.text = properties.tag == "input" ? this.value : (this.textContent || this.innerText || this.innerHTML).replace(/[\s\r\n]+/g, " ").trim();
    properties.href = this.href;

    if (properties.class) {
      let classes_array = properties.class.split(/(\s+)/)
      let trackable_classes = classes_array.filter(value => trackableClassnames.includes(value));
      properties.class = trackable_classes.join(' ');
    }

    ahoy.track("$click", properties);
  });
};

timkrins avatar Mar 03 '22 17:03 timkrins