addEventListener click not working same as console

// Find button and library area element in DOM
const addButton = document.querySelector("#addBook");
const mainBox = document.querySelector("main");
// Create library array
const myLibrary = [];
// The addBook function
function addBook() {
    console.log("FUCK");
    let title = document.querySelector("#bookTitle").value;
    let author = document.querySelector("#bookAuthor").value;
    let pages = document.querySelector("#bookPages").value;
    let read = document.querySelector("#bookTitle").checked;

    let newBook = new Book(title, author, pages, read);

    console.log(newBook);

    addToLibrary(newBook, myLibrary);
};
// create the constructor for the new book
function Book(title, author, pages, read) {
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.read = read;
};
// Supposed to add object to library
function addToLibrary(book, array) {    
    array.push(book);
    console.log(myLibrary)
};
// Add the event listener
document.querySelector("#addBook").addEventListener("onclick", addBook(), false);

When the event listener has the brackets after it it executes on page load and when I remove them it simply doesnt work as intended. When I type the addBook() into the console in chrome it works exactly as intended, creates the object and adds it to the array.
I am lost and have been at this likely simple solution for hours :cry:

The event is just click

You never invoke callback functions directly, as that defeats the purpose of a callback. You pass the definition (the identifier) so it can be invoked later.

You’re referring I think to where I had “onclick”? I sorted that thanks.

Yes. I guess I might have been a tad more clear about that.

onlick is a global event handler HTML attribute, click is the event you listen for in addEventListener.

<button onclick="alert('You clicked me')">Click me</button>
document.querySelector("button").addEventListener("click", () => {
  alert("So much clicking, well I am a button, such is my plight.");
});

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.