jQuery: Disable onclick event using off() not working

Peter G.

Here is a simple example of what I'm trying to do, I have code in HTML and my aim is to disable the three hyperlinks #validate,#organize and #export:

<p id="menuitems" class="inline textcenter">
                        <a id="import" href="javascript:void(0);" onclick="switchScreen('Import');">IMPORT</a> >> 
                        <a id="validate" href="javascript:void(0);" onclick="switchScreen('Validate');">VALIDATE</a> >> 
                        <a id="organize" href="javascript:void(0);" onclick="switchScreen('Organize');">ORGANIZE</a> >> 
                        <a id="export" href="javascript:void(0);" onclick="switchScreen('Export');">EXPORT</a>
                    </p>

When I'm trying to call the following, nothing happend. I'm using jQuery 1.11.4 and I've read that the methods for disabling event listeners have changed since 1.7. So I would like to know if there is an error in my JavaScript code below or some new changes:

$('#validate').off('click');
$('#organize').off('click');
$('#export').off('click');
Me.Name

One way would be to temporarily set the onclick to null, but store the original element onclick in the element or jquery object (e.g. data). With a helper function you can switch the elements on or off:

function setEnabled($a, Enabled ){
    $a.each(function(i, a){          
        var en = a.onclick !== null;        
        if(en == Enabled)return;
        if(Enabled){
            a.onclick = $(a).data('orgClick');            
        }
        else
        {
            $(a).data('orgClick',a.onclick);
            a.onclick = null;
        }
    });
}

Which can be called with something like:

setEnabled($('#validate'), false); 

(also works on jquery objects with multiple elements because of the each)

Example fiddle

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related