I have a link on page <a href="#"... which linked with jquery function. After link was clicked the page scrolled to the top and this seems unnecessary behavior. Is there a way to prevent scrolling?
Asked
Active
Viewed 67 times
0
thinker
- 382
- 4
- 15
-
Yes. Use `event.preventDefault();` – Ionut Jan 04 '17 at 14:15
-
Possible duplicate of [How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?](http://stackoverflow.com/questions/1601933/how-do-i-stop-a-web-page-from-scrolling-to-the-top-when-a-link-is-clicked-that-t) – Quangdao Nguyen Jan 04 '17 at 14:17
3 Answers
1
You can prevent following of # by selecting them and using event.preventDefault():
$(function () {
$('a[href="#"]').click(function (e) {
e.preventDefault();
});
})
Praveen Kumar Purushothaman
- 160,666
- 24
- 190
- 242
0
On click of your button you can prevent the default action using preventDefault():
$('a[href="#"]').on('click', function(event) {
event.preventDefault();
console.log('default action prevented');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#'>Button</a>
Ionut
- 10,707
- 4
- 40
- 69