scruffycoder86
scruffycoder86

Reputation: 549

JavaScript Custom Tracker

I would like to build a tracking system for a Web-based Application built in CakePHP 2.x. The idea is to have all the tracked link having written as below:

<a 
  href="#" 
  class="track-click" 
  data-tracking='{ 
    "trackers": [
      {
        "tracker": "----", 
        "eventId": "---",
        "tracking_options": { 
          "eventTargetUrl": "---", 
          "props": [{ 
            "key": "----", 
            "value": "---"  
          }]
        } 
      } 
    ]
  }'
/>

The javascript that handles the track requests should be able to gather the information that resides inside the data-tracking attribute. This would be done by attaching a click event on the "track-click" class onClick event.

Below is how I use the link above:

$('.track-click').click(function(e){
  //Lets grab the data thats within the data-tracking attribute and do something with it
  var data = $(this).attr('data-tracking');
  alert(data.trackers);
  e.preventDefault();
});

At this present moment if I alert the above I get undefined. If I put $(this).attr('data-tracking').val() on my code I get the error below:

TypeError: $(...).attr(...).val is not a function

What is the best way of manipulating links that have a json data as shown above?

Upvotes: 2

Views: 198

Answers (1)

mohamedrias
mohamedrias

Reputation: 18566

You need to use

var data = JSON.parse($(this).attr('data-tracking'));

This will return you the object.

Else you must use

  var data = $(this).data('tracking');

.data() will return you the object. whereas .attr() will stringify and return that object.

DEMO

Upvotes: 5

Related Questions