event.preventDefault not working as intended

Hi awesome people,

I am working on an app and have a submit button. On clicking the submit button, addEventItemObject function would run but I do not want the page reload on hitting the submit button so I added event.preventDefault() in the addEventItemObject function. Looks like it is not working.
Here is the app link: https://codesandbox.io/s/event-manager-app-s7xui
And here is the code snippet:

  const addEventItemObject = (title, description, startDate, endDate) => {
    event.preventDefault();
  };
  addEventBtn.addEventListener(
    "click",
    addEventItemObject(
      titleInput.value,
      descriptionInput.value,
      startDateInput.value,
      endDateInput.value,
      event
    ),
    false
  );

What am I doing wrong here?

Try to pass event as an argument in the AddEventObject callback function, like this:

const addEventItemObject = (title, description, startDate, endDate, event) => {
    event.preventDefault();
  };
1 Like

You’re adding preventDefault() method to addEventItemObject() which is a function, you need to add it to the submit button event listener like this:

const addEventItemObject = (title, description, startDate, endDate) => {
    
  };
  addEventBtn.addEventListener(
    "click",
    function(event) {
      event.preventDefault();
      addEventItemObject(
        titleInput.nodeValue,
        descriptionInput.nodeValue,
        startDateInput.nodeValue,
        endDateInput.value
      )
    },
    false
  );
1 Like

@mayankverma It did work, thanks Would you help me understand how did it made a difference?

preventDefault() is a method that cancels the default action that belongs to the event, which in submit button’s case is to reload the page, what you were doing was that you were adding preventDefault() method to a function (addEventItemObject) and not the submit button’s (addEventBtn) click event.

1 Like

that make sense but I remember coding the similar way in the past and it worked perfectly. Thank you @mayankverma