views:

856

answers:

4

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");
});
+5  A: 

Try this:

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

$('#flagThis').click(function (evt) {
        $('#reportThis').show("slow");
        evt.preventDefault();
});
$('#submitFlag').click(function (evt) {
        $('#reportThis').hide("slow");
        evt.preventDefault();
});
Darin Dimitrov
Wow thanks a katrillion!!
Trip
+1  A: 

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();
});
Daniel Moura
Why down vote? What is wrong?
Daniel Moura
+1 to cancel, nothing wrong
John Rasch
+2  A: 

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;
});
John Rasch
This works great as well! Thank you!
Trip
+2  A: 

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;
});
SLaks