Jquery: event: event.preventDefault () ;, e not defined

Hi, I have a jquery function that runs on an onclick anchor, the function looks like this:

function dropDown(subid, e) {
 e.preventDefault();
 var sub = '#' + subid;
 // hide all submenus first
 $('.subnav').css({'display' : 'none'});
 //Show the Current Subnav 
 $(sub).css({'display' : 'block'});
}

here is how i can run it:

<a href="#!" onclick="dropDown('sn_cities')" >Cities</a>

However, I get this error: e is undefined

I want to cancel the default onclick event for binding, any help would be appreciated.

+5
source share
2 answers

You do not pass an event object (or anything at all) into a efunction parameter . Try the following:

onclick="dropDown('sn_cities',event);"

I would be inclined to lose embedded JS, though:

<a href="#!" data-dropDown="sn_cities">Cities</a>

$(document).ready(function() {

    $("a[data-dropDown]").click(function(e) {
       e.preventDefault();
       // hide all submenus first
       $('.subnav').hide();
       //Show the Current Subnav 
       $('#' + $(this).attr("data-dropDown")).show();
    });

});
+15
source
function dropDown(subid) {
 var sub = '#' + subid;
 // hide all submenus first
 $('.subnav').css({'display' : 'none'});
 //Show the Current Subnav 
 $(sub).css({'display' : 'block'});
}

<a href="#!" onclick="dropDown('sn_cities'); return false;" >Cities</a>

As a note. Inline-javascript is not recommended. Store your scripts in an external file for clarity.

0
source

All Articles