Mezo
Mezo

Reputation: 85

Submit button not triggering event first time

I'm trying to trap the submit button click event and scroll the page to the top if it's not already there.

For some reason the event doesn't trigger first time, i.e the sliding to the top of page if the scrolling is greater than 0, doesn't happen. It only activates the second time around.

var buttonSearch = function () {
    jQuery(document).ready(function () {
        $("#DashboardSearchButton").submit(function () {
            if (window.scrollY != 0) {
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
        });
    });
};

<input id="DashboardSearchButton" type="submit" value="Search" onsubmit="buttonSearch();" />

Any ideas or suggestions? Am I missing something? Thank you.

Upvotes: 0

Views: 763

Answers (1)

cssyphus
cssyphus

Reputation: 40038

Try it like this:

jQuery(document).ready(function () {
    $("#DashboardSearchButton").submit(function () {
        if (window.scrollY != 0) {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    });
});

<input id="DashboardSearchButton" type="submit" value="Search" />

You either call a function from the element's onclick/onsubmit attribute or you create an eventListener to watch for the event, not both.

jQuery's event listeners are created "under the hood", so to speak, like this:

$("#DashboardSearchButton").submit(function () { //stuff });

You don't ever see the .addEventListener("submit", myFuncName) verbiage - jQuery does that for you.

The reason it didn't work the first time is because you created two event listeners. The first one, triggered by the onsubmit= attribute on the #DashboardSearchButton input, only created the second event listener (the jQuery .submit() handler. Once that 2nd eventListener was created, it now also listened for the submit, and the second time everything worked. However, every time the submit button was clicked, another jQuery event handler would be created.

Upvotes: 1

Related Questions