0

When the user clicks a link, I need to scroll up to the showemaildiv and then fire a click event to open the email data. This works:

$(".showemaillink").click(function(e) {
        e.preventDefault();
        var emailid = $(this).attr('data-emailid');
        var emaildiv = $(".showemaildiv[data-id='" + emailid + "']");

        $('html, body').animate({
            scrollTop: emaildiv.offset().top
        }, 500);

        emaildiv.click();
    });

But to make it a little nicer, I'd like the email to expand after the animate so I'm using a callback. In this case, however, emaildiv.click() is not working although the alert is - what is wrong here?

 $(".showemaillink").click(function(e) {
        e.preventDefault();
        var emailid = $(this).attr('data-emailid');
        var emaildiv = $(".showemaildiv[data-id='" + emailid + "']");

        $('html, body').animate({
            scrollTop: emaildiv.offset().top
        }, 500, function(){
                emaildiv.click();
                alert('callback fired');
            }
        );
    });
Warren
  • 1,984
  • 3
  • 29
  • 60

1 Answers1

0

Your code is ok and working (I've tried it). But there may be a problem with the callback function - it is called twice, for every element you are animating - first time for html and second time for body.

You can read more about it here: Callback of .animate() gets called twice jquery

If you have in your emaildiv click event some actions that negate previous actions (like toggle) it looks like it doesn't work.

Community
  • 1
  • 1
shaggy
  • 1,708
  • 2
  • 15
  • 17
  • Yes - you are correct and I should have realised that the two callbacks were clicking my `emaildiv` twice - one to open and one to shut again!! The code in your link fixed the issue :) – Warren Mar 07 '17 at 05:33