Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel/discard a scroll function?

Tags:

jquery

I've a function for window scroll like this:

function fixDiv() {
//scroll script goes here
}
$(window).scroll(fixDiv);

Now I want to cancel the function when the button is clicked

$('button').on('click',function(){
//cancel the fixDiv() function
// I have tried this:
fixDiv != fixDiv; // and changed/set variable for fixDiv() like var fixDiv = function(){}
});

But seems not working. What way can I cancel the function.

(please note: if again clicked on the button that should be functioning again)


please read the bounty description.

like image 947
Bhojendra Rauniyar Avatar asked Mar 22 '23 03:03

Bhojendra Rauniyar


1 Answers

Try something like that:

DEMO

$('button').on('click', function () {
    this.off = !this.off;
    $(window)[this.off?'off':'on']("scroll", fixDiv )
});

UPDATE

Now if you want to override the function itself, you could use following code:

//using anonymous function as handler, code inside is processing on the fly
$('#anchorAnonymous').on('click',function(){
    fixDiv();
    //any other code, still be called even fixDiv() is overrided...
});
//click to override fixDiv() function
$('#btnoverride').on('click', function () {
    this.override = !this.override;
    //$.noop = function(){} -> do nothing
    fixDiv = this.override?$.noop:storedFixDiv;
});
//this is used to store fixDiv() function
window.storedFixDiv = fixDiv;

Beware, overriding the function won't override the handler if used as referenced method. Because jQuery will create a handler for each event stored in $._data(elem,"events"). To illustrate it, see difference in jsfiddle:

jsFiddle example

like image 166
A. Wolff Avatar answered Mar 31 '23 17:03

A. Wolff