Akhoy
Akhoy

Reputation: 502

How to make an element with opacity 0 unclickable

I know a similar question like this exists here:

CSS3 Element with Opacity:0 (invisible) responds to mouse events

but this question is different.

I'm trying to implement a hamburger navigation menu for mobile devices using jQuery, CSS as mentioned here: Demo.

This mostly works but there's a catch. In the above demo, they are hiding a navigation div which has been fixed to the top (top:0;left:0) by setting opacity:0. While in the above demo this works perfectly, when I implement it, the hidden div responds to clicks and navigates away from the page.

I'm not understanding how this has been disabled in the above demo (double checked the css / js files but no clue). Does anybody else have an idea? I can't really put up a fiddle since I'm trying this in SharePoint and in the fiddle it works. i just need to understand how they've disabled the click events even when using opacity:0 so I can replicate it. Thanks.

Upvotes: 4

Views: 6607

Answers (2)

Farzad Yousefzadeh
Farzad Yousefzadeh

Reputation: 2551

The implementation they used was to use z-index property in order to change the layer of access users mouse will refer to. Meaning that the element with lower z-index would be in down layer of elements with higher z-index. note that default value for z-index is 1. Just give nav element the z-index:-1; and the content Layer z-index:1 or higher to achieve proper react.

Upvotes: 3

Sanderfish
Sanderfish

Reputation: 1530

There are (at least) two things you can do. You could use display: none; or visibility: hidden; instead of opacity: 0;, or you could prevent the menu item being clickable using the preventDefault function in jQuery.

preventDefault would work like this:

$("#hamburger").click(function(e){
  if ($(this).css('opacity')==0) e.preventDefault();
});

Credits to Popnoodles for the code above (Hide clickable links inside div when opacity is 0)

EDIT: I might have misunderstood you're question, since I am now making the hamburger icon unclickable, while I think you ment that the navigation menu needs to be made unclickable, right?

That should work like this:

$('a[class="nav-link"]').click(function(e){
  if ($(nav).css('opacity')==0) e.preventDefault();
});

Add class nav-link to the links in your nav menu.

Upvotes: 5

Related Questions