Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery : event : event.preventDefault(); , e is not defined

hey i have a jquery function that is triggered on an anchor's onclick event the function is as follows:

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'});
}

this is how i am tring to trigger it :

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

However i am getting this error: e is undefined

i want to cancel the default onclick event of the anchor link, any help would be appreciated.

like image 797
Amyth Avatar asked May 31 '12 01:05

Amyth


People also ask

What is e preventDefault () in jQuery?

The preventDefault() Method in jQuery is used to stop the default action of selected element to occur. It is also used to check whether preventDefault() method is called for the selected element or not. Syntax: event.preventDefault() Parameter: It does not accept any parameter.

What is e preventDefault () method?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

What is event preventDefault () and event stopPropagation ()?

preventDefault() prevents the default browser behavior for a given element. stopPropagation() stops an event from bubbling or propagating up the DOM tree. Whereas, return false is a combination of both preventDefault() and stopPropagation() .

What is the opposite of e preventDefault?

As you probably might have already worked out based on the simple explanation above: the opposite of event. preventDefault() is nothing. You just don't prevent the event, by default the browser will allow the event if you are not preventing it.


1 Answers

You're not passing the event object (or anything at all) to the e parameter of the function. Try this:

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

I'd be inclined to lose the inline JS altogether 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();
    });

});
like image 130
nnnnnn Avatar answered Oct 27 '22 19:10

nnnnnn