Reputation: 667
I am using simplecart js. It's a really simple shop with one product. I would like to automatically redirect to the cart page when someone clicks the add to cart button.
The code for adding a product:
<div class="simpleCart_shelfItem">
<h2 class="item_name"> Awesome T-shirt </h2>
<p> <input type="text" value="1" class="item_Quantity"><br>
<span class="item_price">$35.99</span><br>
<a class="item_add" href="javascript:;"> Add to Cart </a></p>
</div>
The listener in simpleCart.js:
/* here is our shelfItem add to cart button listener */
, { selector: 'shelfItem .item_add'
, event: 'click'
, callback: function () {
var $button = simpleCart.$(this),
fields = {};
$button.closest("." + namespace + "_shelfItem").descendants().each(function (x,item) {
var $item = simpleCart.$(item);
// check to see if the class matches the item_[fieldname] pattern
if ($item.attr("class") &&
$item.attr("class").match(/item_.+/) &&
!$item.attr('class').match(/item_add/)) {
// find the class name
simpleCart.each($item.attr('class').split(' '), function (klass) {
var attr,
val,
type;
// get the value or text depending on the tagName
if (klass.match(/item_.+/)) {
attr = klass.split("_")[1];
val = "";
switch($item.tag().toLowerCase()) {
case "input":
case "textarea":
case "select":
type = $item.attr("type");
if (!type || ((type.toLowerCase() === "checkbox" || type.toLowerCase() === "radio") && $item.attr("checked")) || type.toLowerCase() === "text") {
val = $item.val();
}
break;
case "img":
val = $item.attr('src');
break;
default:
val = $item.text();
break;
}
if (val !== null && val !== "") {
fields[attr.toLowerCase()] = fields[attr.toLowerCase()] ? fields[attr.toLowerCase()] + ", " + val : val;
}
}
});
}
});
// add the item
simpleCart.add(fields);
}
}
]);
});
From what I have read it is bad practice to use href="javascript:;" is it a good idea to change it to a click function that will add the item to the cart then go to the cart page or just add the redirect? How do I go about this? Thanks
Upvotes: 0
Views: 297
Reputation: 108472
I’m not sure how the simplecart APi works, but you can try something like:
// add the item
simpleCart.add(fields);
window.location='/cart/'; // change to your cart route
If the cart saves to a server cookie, you might need to put this in a callback.
Upvotes: 1