I have an onClick function directing to an anchor when my button is clicked. When you click the button you can see the # appear in the url and the page quickly jumps to the anchor, but then the # in the url disappears and the page jumps back to the top. I was wondering if anybody knows what is causing this and how to fix it so that the page stays at the anchor.
<button type="submit" class="btn btn-primary" name='search' onClick="location.href='index.php#results'">Search</button>
then later in the page...
<a id="results"></a>
You've attached your click event listener to a submit button.
Presumably, it is inside a form.
Clicking it causes the event to fire, the JS to run, and then the form to submit (because that is the purpose of a submit button).
If you want to link to another part of the page, use a link. If you want it to look like a button, use CSS.
<a href="#results" class="btn btn-primary">Scroll to results</a>
If your goal is to:
Then see this question .
You need to use button inside <a>
tag
<a href="index.php#results">
Search <button type="submit" class="btn btn-primary" name='search' />
</a>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.