PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 27, 2022

[FIXED] How to correctly detach event handler in jQuery

 October 27, 2022     jquery, jquery-events     No comments   

Issue

I have this jQuery function that centers element vertically with scroll support:

    $.fn.center = function () {
        var self = this;
        this.css("position", "absolute");
        this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");            
        $(document).on("scroll", function () {
            self.center();
        });
        return this;
    };

and it's used along with jQuery Block UI plugin:

    $('#cph')
        .block(finalOptions)
        .find('.blockUI.blockMsg')
        .center();

Every time a UI needs to be blocked, I execute second code snippet. But when I unblock UI, I just simply remove it with Block UI API, but I do nothing with scroll event handler. If I block/unblock UI many times, I'll have many event handlers registered to scroll event - which I guess is bad. But I don't know how to properly address that issue. Could you advise?


Solution

use jquery off

// assume you have a method for reuse purpose
function YourFunction(){
    // do something
};

$(document).on("scroll", YourFunction);
$(document).off("scroll", YourFunction);

Note that anonymous function won't work in this case unless you want to detach all event handlers:

$(document).off("scroll");

You can also specify a "namespace" when "on" and "off" events:

// delegate events under the ".validator" namespace
$(document).on("click.validator", function(){
    // do something
});

// remove only event handlers in the ".validator" namespace
$("form").off(".validator");


Answered By - phnkha
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing