Jquery - .click() that doesnt scroll the page

487 views Asked by At

I'm about to make a function on jQuery like this:

$(document).ready(function() {
    $('#header_rules').click(function() {
      // here i define myFunction()
    });
});

<a id="header_rules" href="#">RULES</a>

instead of

 <a id="header_rules" href="#" onClick="myFunction();return false">RULES</a>

But I don't know how to prevent scrolling to the top of the page using jQuery after someone clicks the link.

In fact, I'll total get rid about native JS, which could yield some trouble (that's why I use a JS framework like jQuery).

Any help? Cheers

3

There are 3 answers

2
ThiefMaster On BEST ANSWER

Call e.preventDefault(); where e is the first argument of your click handler:

$(document).ready(function() {
    $('#header_rules').click(function(e) {
        e.preventDefault();
        // here i define myFunction()
    });
});

<a id="header_rules" href="#">RULES</a>
2
Matrym On

The below will also work, but it'll stop other click events on the item, I think.

(document).ready(function() {
    $('#header_rules').click(function() {
      // here i define myFunction()
    return false;
    });
});
1
Victor On

What ThiefMaster said, and you could also inclue return false; inside your function intead of inline.