23

I've got a page with some questions and answers, the answers are collapsed by default. When they click the question I expand the hidden answer-div. The problem is that when I click these questions, the window jump to the top of the screen. This is not a huge problem, but I find it annoying, because I have to scroll down to the question again.

The links simply looks like this:

<a href="#" id="myID">Myquestion</a>

And I've used jQuery and .click as event-listener.

Are there any simple ways to avoid this, or do I have to use .scroll and finding the coordinates of the question? I'd rather avoid this.

EDIT: I know that I can use anchors to do this, but I'd like to avoid any jumping of the screen at all.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
  • 2
    You shall mark the answer is correct, and don't copy&paste this inside your question. If you have a diff solution, you post as answer. – Ratata Tata Nov 23 '11 at 10:37
  • 2
    Possible duplicate of [How to prevent a click on a '#' link from jumping to top of page in jQuery](https://stackoverflow.com/questions/3252730/how-to-prevent-a-click-on-a-link-from-jumping-to-top-of-page-in-jquery) – Organic Advocate Oct 02 '17 at 17:21

12 Answers12

25

You need to add preventDefault() to your click handler. This will stop the browser executing it's own link handler, and will only run the code you specify.

Example:

$("#myID").click(function(e) {
    e.preventDefault();
    // Do your stuff
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    Ah, of course. I am so stupid. But this did not work in IE7. I'd like to add support for IE7 and/or IE8. Are there any ways to do this as well? – OptimusCrime Nov 23 '11 at 10:28
  • 1
    Bad research by me, I found this in another question `if(e.preventDefault){ e.preventDefault()} else{e.stop()};` Thanks. Case closed. – OptimusCrime Nov 23 '11 at 10:30
  • 2
    `preventDefault()` should work in all browsers if you're using jQuery. You can also just return false from your event handler. – nnnnnn Nov 23 '11 at 10:51
  • Well, for some reason it does not work in older versions of IE – OptimusCrime Nov 23 '11 at 23:12
  • Having same problem with IE7 on skip links it doesn't work with e.preventDefault(); – Josh Bedo Sep 06 '12 at 20:08
6

Don't use A tags for tasks that are not navigation-related. It is not semantic markup, and doesn't degrade gracefully. Use buttons instead.

Jonas Høgh
  • 10,358
  • 1
  • 26
  • 46
  • Good idea, problem is that the text itself should be the link, therefor I did not go for the button. But I guess it would be smarter to use span or something else for this. I'll keep that in mind next time, don't want to rewrite my entire parser. – OptimusCrime Nov 23 '11 at 23:13
5

You can do it very simple: Just add ! in the end of your href:

<a href="#!" id="myID">Myquestion</a>

The alternative jQuery ways are:

$("#myID").click(function(e) {
    e.preventDefault(); // one way 
    return false; // second way prevent default click action from happening
});
SaeX
  • 17,240
  • 16
  • 77
  • 97
David
  • 633
  • 8
  • 6
  • 1
    Warning: Google Analytics doesn't like hrefs with a `#!` value and will throw this error into the log: `Syntax error, unrecognized expression: #!` – Marcel Gruber Oct 07 '20 at 21:18
2

Actually, the easiest way to do this is to remove the href attribute from your anchor tag. As of HTML5, anchor tags don't need to include href attributes to be semantic.

So

<a id="myID">Myquestion</a>

instead of

<a href="#" id="myID">Myquestion</a>

This works in IE8+, Chrome, and Firefox. Note that :link css styles won't apply to anchor tags that don't include href attributes.

If you need the href attribute and/or IE7 compatibility, then

$("#myID").click(function(e) {
if(e.preventDefault)
    e.preventDefault();
else
    e.stop();
});

is probably the best way to go.

craig
  • 487
  • 2
  • 8
  • 18
2
$("#myID").click(function(e) {
    if(e.preventDefault)
        e.preventDefault();
    else
        e.stop();
});

e.preventDefault()alone did not work in older versions of IE.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
1
$('a').click( function() {
  if ($(this).attr("href") == window.location.hash) {
    event.preventDefault()
  }
});
zamuka
  • 796
  • 2
  • 9
  • 21
0

$('body').on('click', '[href^=#]', function (e) { e.preventDefault() });

if the selector ex.."body" is there during the initial render then use the any selector .. id ... to target the general to have jQuery (as of 1.8.2) iterate over. the "On handler invoke a method called "bind" which is used for newly added content to the DOM",. Using the "[href^=#] will select any href that are in the section tag but you can replace section with anything or nothing and it applies a cancellation to the click event. This technique is great for dynamically created content to the DOM

Cain
  • 1
  • 1
0

If you add a "\" to the "#" it will prevent from going to the top.

<a href="#\" id="myID">Myquestion</a>
Nuno cruz
  • 215
  • 3
  • 10
0

HTML:

<a id="like-post" href="#\">like</a>

JavaScript:

$('body').delegate('#like-post','click',function(e) {
     e.preventDefault();
     .....
});
Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
  • 4
    Why would you 1) answer a question that has an accepted answer almost 6 years ago? 2) use a **depreciated** method in your answer? – JNYRanger Jun 28 '17 at 19:07
0

You are looking for event.preventDefault (see jQuery API).

$(...).click(function(e) {
  e.preventDefault();
  // your code
});
Marcel Jackwerth
  • 53,948
  • 9
  • 74
  • 88
0

Inside your function of:

And I've used jQuery and .click as event-listener.

Will look something like:

$("#myID").click(function(){});

Change this to (don't forget the param e inside function(e):

$("#myID").click(function(e){
    e.preventDefault();
});
Kijewski
  • 25,517
  • 12
  • 101
  • 143
Niels
  • 48,601
  • 4
  • 62
  • 81
0

Example with nice scrolling to answer content:

$("#question_title").click(function(){
  var $answer=$("#answer");
  $answer.slideDown();
  $.scrollTo( $answer, 800 );
  return false;
});

I'm used jQuery scrollTo plugin.

rogal111
  • 5,874
  • 2
  • 27
  • 33