Search code examples
javascriptjqueryhtmlfilteringadobe-analytics

How can you add a string to an onclick function based on a link/filter clicked?


Would like to use jQuery or js.

I have filters that change the way a page displays. I am tracking the clicks on the images that are filtered by using a onclick on the anchor tag. I want to pass the link/filter that was selected along with the text I am currently housing in the onClick.

I have the filters and trackLink working. I just need to append the data-filter value to the onclick in the anchor tag.

Here is the example to shine the light on the situation...

Filters

<a href="#" data-filter=".optionone">Option One</a>
<a href="#" data-filter=".optiontwo">Option Two</a>

Content Being filtered - same page

<div class="item">
    <a onclick="trackLink('Text I Want', 'Text I want')" href="1.aspx">
        <img src="1.jpg" alt="1" />
        <div>Test</div>
    </a>
</div>  

<div class="item">
    <a onclick="trackLink('Text I Want', 'Text I want')" href="2.aspx">
        <img src="2.jpg" alt="2" />
        <div>Test</div>
    </a>
</div>  

What I want - Pass the data-filter value.

<div class="item">
    <a onclick="trackLink('Text I Want', 'Text I want' + the filter name as it is being click passed)" href="1.aspx">
        <img src="1.jpg" alt="1" />
        <div>Test</div>
    </a>
</div>   

Solution

  • You can't really append text like that inside of a function inside of an HTML element.

    What I would do is switch up the HTML some by adding a class to the filters, and moving the "Text I want"s to their own data value:

    <a href="#" class="filter" data-filter=".optionone">Option One</a>
    <a href="#" class="filter" data-filter=".optiontwo">Option Two</a>
    ...
    <div class="item"><a data-first-text="Text I Want" data-second-text="Text I want" href="1.aspx"><img src="1.jpg" alt="1" /><div>Test</div></a></div>
    

    Then use jQuery to call your function:

    var filter_text;
    
    $('a.filter').click(function(event) {
        // set the filter text to whatever the filter is
        filter_text = $(this).data('filter');
    });
    
    $('.item a').click(function(event) {
        var first_text = $(this).data('first-text');
        var second_text = $(this).data('second-text');
    
        // call trackLink with your desired texts
        trackLink(first_text, second_text + filter_text);
    });
    

    Fiddle