2

I'm having some trouble trying to delay a function from executing on a click event.

I have a series of links, each one's href being a unique YouTube video embed URL. What I'm trying to do is switch the source of an iframe on my page, using one of these YouTube URLs. But I'm trying to delay the switch while my page scrolls back to the top.

I have created a Fiddle that better illustrates my point.

I originally had this JS function;

$(".play-video").click(function(e) {
    $("html, body").animate({ scrollTop: 0 }, 500);
    $("#video-frame").attr("src", $(this).attr("href"));
});

Which worked in both scrolling the page and switching the iframe, but scrolling the page while switching the iframe source made the scroll animation a bit jerky which isn't ideal.

Any help with this would be great.

Thanks in advance.

3
  • 2
    pass a complete function to jquery's animate, which will only run once the animation is complete Commented Jul 27, 2015 at 13:25
  • 2
    ⇑⇑⇑ like this e.g: jsfiddle.net/g882Lc79/2 or maybe better jsfiddle.net/g882Lc79/4 Commented Jul 27, 2015 at 13:26
  • @A.Wolff Perfect!! Thank you Commented Jul 27, 2015 at 13:31

1 Answer 1

2

There's no need to mess around with setInterval or setTimeout. The animate method accepts a complete callback to be run when the animation is complete.

$(".play-video").click(function(e) {
    $("html, body").animate({ scrollTop: 0 }, 500, function() {
       $("#video-frame").attr("src", $(this).attr("href"));
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.