Search code examples
javascriptjqueryhoverclickjquery-data

How Store and Disable Event of another element Temporary


I am looking for a way to manage the events. I have a hover function for element A, and click function for element B. I want to disable A`s hover function temporary while the second click of B.

I am looking for a way that not necessary to rewrite the hole function of A inside of B. Something very simply just like "Store and Disable Event, Call Stored Function"

I found some technique like .data('events') and console.log. I tired but failed, or maybe I wrote them in a wrong way.

Please help and advice!

$(A).hover();

$(b).click( 

     if($.hasData($(A)[0])){   // if A has event,
             //STORE all the event A has, and disable
     }else{
            //ENABLE the stored event for A
     }
 );

Solution

  • I think that what you want to do is something like this (example for JQuery 1.7.2):

    $("#a").hover(function(){alert("test")});
    $("#a")[0].active=true;
    
    $("#b").click(function(){
        if($("#a")[0].active){
            $("#a")[0].storedEvents = [];
            var hoverEvents = $("#a").data("events").mouseover;
            jQuery.each(hoverEvents , function(key,handlerObj) {
                $("#a")[0].storedEvents.push(handlerObj.handler);
            });
            $("#a").off('hover');
        }else{
            for(var i=0;i<$("#a")[0].storedEvents.length;i++){
                $("#a").hover($("#a")[0].storedEvents[i]);
            }
        }
        $("#a")[0].active = ($("#a")[0].active)==false;
    });​
    

    JSFiddle Example

    But there are a couple of things that you must have in consideration:

    • This will only work if you add the events with JQuery, because JQuery keeps an internal track of the event handlers that have been added.
    • Each version of JQuery handles data("events") differently, that means that this code may not work with other version of JQuery.

    I hope that this helps.

    EDIT:

    data("events") was an internal undocumented data structure used in JQuery 1.6 and JQUery 1.7, but it has been removed in JQuery 1.8. So in JQuery 1.8 the only way to access the events data is through: $._data(element, "events"). But keep in mind the advice from the JQuery documentation: this is not a supported public interface; the actual data structures may change incompatibly from version to version.