T94
T94

Reputation: 109

On Click with a case switch

I have a few on click events who actually are doing the same thing. Someone told me I should use a case switch for this so I can reduce my code. But I don't know how to do that in combination with a on click event.

$( "#wishlist_top" ).on( "click", function() {
    window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
    hj('tagRecording', ['Klikt op "wishlist" in menu']);
});

$( ".wishlist" ).on( "click", function() {
    window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
    hj('tagRecording', ['Klikt op "plaats op wishlist"']);
});

$( ".product_size" ).on( "click", function() {
    window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
    hj('tagRecording', ['Klikt op "maat advies"']);
});

$( ".product_stock" ).on( "click", function() {
    window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
    hj('tagRecording', ['Klikt op "maat niet beschikbaar?"']);
});

if ( $('*').hasClass('404') ) {
    window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
    hj('tagRecording', ['Klant is op een 404 pagina gekomen']);
}

Thank you!

Upvotes: 0

Views: 813

Answers (2)

WillardSolutions
WillardSolutions

Reputation: 2314

Another option here is to use data attributes in your markup. Add the message you want to pass to a data-text attribute in each of your elements -

<a href="#" class="product_stock" data-text='Klikt op "wishlist" in menu'>Foo</a>

And then you can set up one JS handler, which grabs the text from your data attribute:

$( ".product_stock" ).on( "click", function() {
    window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
    hj('tagRecording', $(this).data("text"));
});

Of course this only works if you have control over the creation of the markup.

Upvotes: 1

Scott Stevens
Scott Stevens

Reputation: 2651

While you can use a switch/case for this, it might not be the best idea. You still need to listen for click events on each class/ID, so I'd make a function and call that with the specific string.

Using your code from above, you can make a function like so:

function tagRecording(value) {
    window.hj=window.hj||function(){(hj.q=hj.q||[]).push(arguments)};
    hj('tagRecording', [value]);
}

Now just use a click listener like so:

$( "#wishlist_top" ).on( "click",
    function() { tagRecording('Klikt op "wishlist" in menu'); } );

So next time you want to change your code, you just change the tagRecording function (you can rename it however you like).

Upvotes: 3

Related Questions