16

If I do this I can prevent default on form submit just fine:

document.getElementById('my-form').onsubmit(function(e) {
   e.preventDefault();
   // do something
});

But since I am organizing my code in a modular way I am handling events like this:

document.getElementById('my-form').addEventListener('onsubmit', my_func);

var my_func = function() {
   // HOW DO I PREVENT DEFAULT HERE???
   // do something
}

How can I prevent default now?

  • 3
    The same way. The browser (well, decent ones) pass the event object as a parameter. – Pointy Jul 17 '13 at 20:01
  • 2
    LOL if you want to be bad you could always put `
    `
    – Banning Jul 17 '13 at 20:03
  • Note: When using the [`onclick` property](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onclick), just set it: `elem.onclick = function () { ... };`. Otherwise, you're trying to call a previous handler with the new one as an argument. – Jonathan Lonowski Jul 17 '13 at 20:05
  • @JonathanLonowski Haha hopefully that was a typo – Ian Jul 17 '13 at 20:05
  • http://stackoverflow.com/questions/7410063/how-can-i-listen-to-the-form-submit-event-in-javascript – Banning Jul 17 '13 at 20:10

3 Answers3

42

The same way, actually!

// your function
var my_func = function(event) {
    alert("me and all my relatives are owned by China");
    event.preventDefault();
};

// your form
var form = document.getElementById("panda");

// attach event listener
form.addEventListener("submit", my_func, true);
<form id="panda" method="post">
    <input type="submit" value="The Panda says..."/>
</form>

Note: when using .addEventListener you should use submit not onsubmit.

Note 2: Because of the way you're defining my_func, it's important that you call addEventListener after you define the function. JavaScript uses hoisting so you need to be careful of order of things when using var to define functions.

Read more about addEventListener and the EventListener interface.

Mulan
  • 129,518
  • 31
  • 228
  • 259
  • 2
    No, the `return false` doesn't work like you think. Maybe in jQuery, but definitely not with `addEventListener` – Ian Jul 17 '13 at 20:03
2

All you have to do is add a parameter to your function and use it inside.

var my_func = function(event) {
   
   event.preventDefault();
   
}

The parameter inside now represents the parameter from the addEventListener.

Emrah Tuncel
  • 678
  • 8
  • 13
-1

i known this is old, but just for the sake of it. try

document.getElementById('my-form').addEventListener('onsubmit', 
function(event){event.preventDefault();my_func();});
var my_func = function() {
// HOW DO I PREVENT DEFAULT HERE???
// do something
}
  • When using EventListeners, use the event name and not the action. In the case of your answer, it should be addEventListener('click', ...) not addEventListener('onclick', ...) – Ebuka Feb 13 '21 at 09:52