Rich-text Reply

Adding An Add To Cart Link

KO 10-26-16

Adding An Add To Cart Link

Hello, 

 

I am attempting to add an "Add To Cart" link for products below their 1-5 star rating on thumbs pages.

 

I think the best approach might be to use the .insertAfter() technique for the class name of the ratings div, but was unsure. Would something like this work?:

 

<div class="addToCartLink"><a href="/checkout/cart">Add To Cart</a></div>

$('.addToCartLink').insertAfter('.rating-container')

Any and all feedback here is greatly appreciated. 

 

Thank You

KO
Level 2

JasonDahlin 10-27-16
 

Re: Adding An Add To Cart Link

[ Edited ]

hi @KO,

The idea is correct, but your syntax is not.

 

To insert a link, I'd go with something like the following:

var newLink = "<div class='addToCartLink'><a href='/checkout/cart'>Add To Cart</a></div>";
$(newLink).insertAfter('.rating-container');

You will need to make sure that the link you add actually performs an add to cart.  The example above is merely a link to the the cart page.

 

--Jason Dahlin
Analytics and Testing Guru Smiley Happy
KO 10-27-16
 

Re: Adding An Add To Cart Link

Hi There, 

 

Thanks for responding. I was actually able to get it done this way:

 

$(".rating-container").after("<div id=\"optimizely_795437338\"><strong>ADD TO CART</strong></div>");
$("<div id=\"optimizely_795437338\"><strong>Add To Cart</strong></div>").attr({"href":"/checkout/cart"});

/*injects a div after the ratings container
"ADD TO CART"link clicks through to color/size selection
on desktop this button clicks through to QuickView
kept all caps to mirror desktop experience*/

Thanks for your help!

KO
Level 2
robertchan 10-27-16
 

Re: Adding An Add To Cart Link

While your code functions as expected, I'd recommend refactoring it like so:

 

var referenceElem = ['<div id="optimizely_795437338">',
                     '<strong>ADD TO CART</strong>',
                     '</div>'].join('');

$(".rating-container").after(referenceElem);
$(referenceElem).attr({"href":"/checkout/cart"});

This is much cleaner, and easier to read for anyone else working on the code. 

Robert Chan

KO 10-27-16
 

Re: Adding An Add To Cart Link

thanks, that is a lot cleaner.

what's the purpose of using the .join(''); at the end of the variable declaration?
KO
Level 2
robertchan 10-27-16
 

Re: Adding An Add To Cart Link

Anytime, using join allows you to connect all the different strings within the brackets as one large string. This is helpful if you're adding a lot of HTML.
Robert Chan

KO 10-27-16
 

Re: Adding An Add To Cart Link

Awesome -- thank you
KO
Level 2
robertchan 10-28-16
 

Re: Adding An Add To Cart Link

Anytime and glad to help!
Robert Chan

juliofarfan 10-28-16
 

Re: Adding An Add To Cart Link

Another workaround can be something like this

$("#yourelement").mousedown(function (){
window.open('yourlink.com', '_blank');
});