greenpool
greenpool

Reputation: 561

How to stop link button refreshing the page

In my code I'm using a link button called updateLogButton which shows/hides a div. Because I use a link button everytime its clicked focus is moved to the beginning of the page. How can I stop this default behaviour?

Jquery snippet:

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

$('#updateLogButton').click(function() {

    if ($('#updateLogText').is(':visible')){

        //hide div if content is visible
        $('#updateLogText').fadeOut();

    }else{

        $('#updateLogText').fadeIn();       
    }

});

HTML code:

<tr>
    <td><a href="#"  id="updateLogButton">Update Log</a></td>
</tr>
<tr>
    <td colspan="3" >
        <div id="updateLogText" style="width:100%;">
            <?php echo $data['updates']; ?>
        </div>

    </td>
</tr>

EDIT: example of what i mean: http://jsfiddle.net/cF4Bb/7/

Upvotes: 0

Views: 2966

Answers (5)

Russell Gutierrez
Russell Gutierrez

Reputation: 1385

You can also try changing your href to:

<a href="javascript:void(0);" id="updateLogButton">Update Log</a>

Upvotes: 1

XXX
XXX

Reputation: 87

Remove the href="#" from

<td><a **href="#"** id="updateLogButton">Update Log</a></td>

to

<td><a id="updateLogButton">Update Log</a></td>

note that this may remove the 'hyperlink' like text; which you can re-apply using css.

[EDIT: ADDED] Alternatively you can use LinkButton instead as follows:

<asp:LinkButton id="btnLink" Text="Update Log" **onclick**="javascript:ShowHide(); return false;"/>

You will have to write your own javascript function. **Note: can't remember on top of my head whether it onclick or onclientclick but you get the idea.

Upvotes: 0

Musa
Musa

Reputation: 97672

To prevent the default action when the link is clicked you can return false from the click handler or call event.preventDefault where event is the event object passed to the click handler.

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

$('#updateLogButton').click(function(event) {

    if ($('#updateLogText').is(':visible')){

        //hide div if content is visible
        $('#updateLogText').fadeOut();

    }else{

        $('#updateLogText').fadeIn();       
    }
    event.preventDefault();
    //or return false;
});

Upvotes: 5

SReject
SReject

Reputation: 3936

Return false from the one click event

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

$('#updateLogButton').click(function() {

    if ($('#updateLogText').is(':visible')){

       //hide div if content is visible
        $('#updateLogText').fadeOut();

    }else{

        $('#updateLogText').fadeIn();       
    }
    return false;
});

Upvotes: 0

LiamB
LiamB

Reputation: 18586

Add return false

$('#updateLogButton').click(function() {

    if ($('#updateLogText').is(':visible')){

        //hide div if content is visible
        $('#updateLogText').fadeOut();

    }else{

        $('#updateLogText').fadeIn();       
    }

     return false;
});

Upvotes: 2

Related Questions