Trip
Trip

Reputation: 27114

jQuery click brings me to top of page. But I want to stay where I am

I have a simple click and show, click and hide button, but when I click it, the page anchors at the top of the page. Is there anyway to prevent this? So that when I click the button, I stay at the same place in the browser?

My code is..

$('#reportThis').hide();

$('#flagThis').click(function () {
    $('#reportThis').show("slow");
});
$('#submitFlag').click(function () {
    $('#reportThis').hide("slow");
});

Upvotes: 7

Views: 12344

Answers (5)

James M
James M

Reputation: 239

If you're using a <button> element don't forget to set the type attribute.

<button type="button">My Button</button> 

Some browsers default to submit which will bring you back to the beginning of your page.

It's where I was going wrong anyway and saw nothing here about it so thought I'd share my two cents for future readers.

Upvotes: 0

SLaks
SLaks

Reputation: 887453

Change the hyperlinks to point to a non-existent anchor, like this:

<a href="#IDontExist" id="flagThis">Flag</a>

Or, make your handlers return false, like this:

$('#reportThis').hide();

$('#flagThis').click(function () {
    $('#reportThis').show("slow");
    return false;
});
$('#submitFlag').click(function () {
    $('#reportThis').hide("slow");
    return false;
});

Upvotes: 3

John Rasch
John Rasch

Reputation: 63445

Try returning false in the click function:

$('#reportThis').hide();

$('#flagThis').click(function () {
        $('#reportThis').show("slow");
        return false;
});
$('#submitFlag').click(function () {
        $('#reportThis').hide("slow");
        return false;
});

Upvotes: 4

Daniel Moura
Daniel Moura

Reputation: 7966

You probably are binding this clicks to a <a> tag which has a default action. To prevent this you can use another tag like <div> or you can do this:

$('#flagThis').click(function (event) {
        $('#reportThis').show("slow");
        event.preventDefault();
});

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

Try this:

$('#reportThis').hide();

$('#flagThis').click(function (evt) {
        $('#reportThis').show("slow");
        evt.preventDefault();
});
$('#submitFlag').click(function (evt) {
        $('#reportThis').hide("slow");
        evt.preventDefault();
});

Upvotes: 18

Related Questions