Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onclick except if element is 'someElement'

I am wondering if there is a way to exclude certain elements on a function. For example:

window.onclick = doThis() except if the element clicked is a 'ul' element.

Something like that. I know that it would probably have to be written like this:

function doThis() {
  if (this item clicked is NOT 'ul') { 
     function xyz();
}}

window.onclick = doThis();

I am just not sure if there is an "exception" in javascript. Can someone please help. thanks.

ok so here is my full code because it is still not working:

<script type="text/javascript">
function ddMenu() {
var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

function ddMenu_open(e)
{
   //ddMenu_canceltimer();
   ddMenu_close();
   var submenu = $(this).find('ul');
    if(submenu){
        ddmenuitem = submenu.css('visibility', 'visible');
        //return false;
        //preventDefault();

    }
   //return true;
}

function ddMenu_close()
{  if(ddmenuitem) ddmenuitem.css('visibility', 'hidden'); }

function ddMenu_timer()
{ closetimer = window.setTimeout(ddMenu_close, timeout); }

function ddMenu_canceltimer()
{  if(closetimer)
   {  window.clearTimeout(closetimer);
      closetimer = null;}}

$(document).ready(function()
{  $('#ddMenu > li').bind('click', ddMenu_open);
   $('#ddMenu li ul').bind('click', ddMenu_timer);
   //$('#ddMenu > li').bind('mouseout',  ddMenu_timer);
   //$('#ddMenu > li').bind('mouseover', ddMenu_canceltimer);

});

document.onclick = function(ev){
    if(ev.target.nodeName !== 'ul')  {
        ddMenu_close();
    }
};


}
</script>

i added the target.nodeName !== code that was suggested below but it is still not working. When i click a ul it still closes my menu. thank you.

like image 809
user982853 Avatar asked Dec 21 '22 04:12

user982853


1 Answers

window.onclick = function(ev){
    if( ev.target.nodeName !== 'UL' ){
        xyz();
    }
};

What we're doing here is making the event object a parameter. This way we can get the target of the click event. We're doing exactly that here—we check if the target is a ul element. If not, run the function.

Also, just for future reference, you have to assign the function to the onclick. So first assign the function to a variable, and then assign the variable to the onclick (without parentheses). I read this somewhere...I'll try to pull that up.

like image 103
Purag Avatar answered Jan 03 '23 00:01

Purag