I’m trying in different ways to create a small scrolling method which can take an optional effect callback function. Imagine I can run scrollToEl(el, flash) which would first scroll down to the element and the flash it. How would I normally go about this?
This is what I’ve done..but it’s not really working.
scrollToEl : function(el, callback) {
// flash the selected product
var self = this;
$('html, body').animate({
scrollTop: el.offset().top - 50
}, 1000, 'swing', callback); // how to pass el here as well paired with callback?
}
flash : function(el) {
// flash the selected product
el.animate({
opacity : 0.4
}, 100, 'swing', function() {
el.animate({
opacity : 1
}, 1000, 'swing');
});
},
I want to use it like this:
var el = $('#element');
scrollToEl(el, flash); // how to pass in to the callback function flash?
You can use a closure:
More about closures: Closures are not complicated
If you want the callback to receive the element as
this, you can usejQuery.proxyinstead of your own wrapper function:It comes to the same thing, because
proxycreates a function. But it doesn’t introduce a closure over the context of the call toscrollToEl.