0

I have a small script that runs when a customer presses add to cart that moves to the top of the page to ensure that they see the success message and that the item has been added to their cart. However, if there is a problem with a selection on a complex product and it fails validation there is a bounce effect as the validation script tries to move the page to the validation error and my script tries to move to the top of the page.

Here is my script (which is in my default.js file):

function animateToTop(e) { e.preventDefault(); var scrollToTop = window.setInterval(function() { var pos = window.pageYOffset; if ( pos > 0 ) { window.scrollTo( 0, pos - 20 ); } else { window.clearInterval( scrollToTop ); } }, 24); }

Here is the function call in the addtocart.phtml file:

<button class="btn1 btn1-atc" type="button" title="<?php echo $buttonTitle ?>" onclick="productAddToCartForm.submit(this); animateToTop(event)"><span><b class="ico"></b><b><?php echo $buttonTitle ?></b></span></button>

How can I add a check that validation has been passed before running this?

1

Try

//var productAddToCartForm = new VarienForm('product_addtocart_form');
if (productAddToCartForm.validator.validate()) {
   //pass
}
else{
   //fail
}

Assuming this is on your product detail page, then take a look app/design/frontend/yourtheme/default/template/catalog/product/view.phtml

    <script type="text/javascript">
    //<![CDATA[
        var productAddToCartForm = new VarienForm('product_addtocart_form');
        productAddToCartForm.submit = function(button, url) {
            if (this.validator.validate()) {

                //you code here

                var form = this.form;
                var oldUrl = form.action;
                if (url) {
                   form.action = url;
                }
                ...

see https://github.com/OpenMage/magento-mirror/blob/magento-1.9/app/design/frontend/rwd/default/template/catalog/product/view.phtml#L125

4
  • Thanks, where do I put my existing code in this?
    – Hugh
    Jul 22 '15 at 14:41
  • You can either replace '//pass' with animateToTop(e) (not sure why you are passing e) or copy the content of the function instead Jul 22 '15 at 14:44
  • I there - thank you for your help but I still don't quite understand. I have edited the original question as I have a function call in the addtocart.phtml file which references a script in the main default.js file. I assume I need to wrap the script in the default.js file in the conditional statement above but am not sure whether that is the correct approach.
    – Hugh
    Jul 22 '15 at 17:54
  • One way is to edit this function productAddToCartForm.submit the path is listed above Jul 22 '15 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.