0

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.

1
  • 1
    Can you not see that buttonSearch() creates a new event handler for the search button? ie only when you click the button is the click button event handler created. Remove the onsubmit= and the var buttonSearch=function(){ (and }) lines and you're good to go. Commented Mar 12, 2021 at 14:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.