jQuery: Enable Click Event for Some Anchor Elements

jQuery provides a very easy way to disable click events for any DOM element. And you can also disable click event for all Dom elements with few lines of code. But then what if you want to enable click event for some elements? For example, if a click event is disabled for all anchor elements, but there is a situation where you need to enable click event for one or more anchor elements. How do you implement it?  In this post you'll see how to address this requirement.

HTML

For this demo, there are 2 anchor tags. One with a class “allowClick,” for which click should be allowed. For all other anchor tags, click should be disabled.

   <a href="#">Click Me!!!!</a>
   <a href="#">No Click</a>

jQuery

First, here is jQuery code to disable click event for all anchor tags. The following jQuery code will disable the click event for all anchor tags present in the page.

$('a').click(function(e) {
    console.log('Click Disabled!!!.');
   e.preventDefault();
 });

Now, how do we allow the click event for some anchor elements? To allow the click event, you need to attach click events again to that element. Following jQuery code will attach click event to all elements with css class named “allowClick”.

$('.allowClick').click(function(e) {
    console.log('allowClick Worked!!!.');
 });

So the complete jQuery code is:

$('a').click(function(e) {
    console.log('Click Disabled!!!.');
    e.preventDefault();
 });
$('.allowClick').click(function(e) {
    console.log('allowClick Worked!!!.');
 });

In this case when element with CssClass “allowClick” will be clicked, then first $('a').click() would be called and then its own attached click event. Here is the screenshot:

Screen Shot 2016-11-14 at 12.00.41 PM



Responsive Menu
Add more content here...