Tysaic
Tysaic

Reputation: 31

How to call a function in an event like click in Jquery?

My problem is when i want to call a function in an event click into two id, the errors is TypeError: e is undefined

code here:

function slide(e) {
    e.preventDefault();
    $("#wrapper").toggleClass("toggled");
};
$("#menu-toggle").click(slide());
$("#menu").slide();

Upvotes: 0

Views: 94

Answers (3)

Ahmed Eid
Ahmed Eid

Reputation: 4804

you don't need to call the function , you just pass it without ()

function slide(e) {
    e.preventDefault();
    $("#wrapper").toggleClass("toggled");
};


$("#menu-toggle").click(slide);
$("#menu-toggle").click(function(e){
  // here you can call however many functions you want. 
  slide(e)
  console.log("#menu-toggle clicked")
  // ...
});
$("#menu-toggle").click($("#menu").slide);

Upvotes: 1

sliptype
sliptype

Reputation: 2964

You are calling the slide function immediately instead of passing a reference of it to the click handler. Here is what you need:

function slide(e) {
    e.preventDefault();
    $("#wrapper").toggleClass("toggled");
};
$("#menu-toggle").click(slide);

Upvotes: 1

h1b9b
h1b9b

Reputation: 1050

You should add an event listener and replace

$("#menu-toggle").click(slide());

by

$("#menu-toggle").on('click', slide);

And then when you call click the listener will trigger

But if you want to call the function just one-time use

$("#menu-toggle").click(slide);

Upvotes: 1

Related Questions