Gordnfreeman
Gordnfreeman

Reputation: 1625

Stopping the Page from going to the top with a div is unhidden/hidden with jQuery

I know the title of this post is somewhat confusing, but I could not think of a way to explain it in such a short section.

Basicly the my question is this: I created a program to track events, there can be alot of events on a single page so I decided to hide the details on each item initially, when the user clicks the "view details" button the details div is unhidden and the user can view them, if they click it again then they are hidden.

The problem is that if the user is far down on the page and clicks the link it shoots them back to the top of the page (while still showing the details) the user has to scroll all the way back down the page to read the entry. Does anyone know of a way to keep the user in the same place they were when they clicked the button?

Thanks, Let me know if i can provide anything else.

Upvotes: 0

Views: 136

Answers (6)

Ferran Basora
Ferran Basora

Reputation: 3147

May be you forgot the return false?

$("a.detail").click(function(){

    // Loading the div contents... 

    return false; // Don't forget this
});

Upvotes: 0

Chris Baker
Chris Baker

Reputation: 50612

Without seeing your HTML, I can only guess... but if you're using something like this:

<a href="#" id="details12" onclick="show_details();">show details</a>

...when the user clicks that link, they are going to the top of the page. That's because of the href property you've got there - '#' is an empty anchor and will shoot the page up to the top. All you need to do is return false from your event:

<a href="#" id="details12" onclick="return show_details();">show details</a>

function show_details(e) {
  // show the details

  return false;
}

You can also use event.preventDefault as described here: https://developer.mozilla.org/en/DOM/event.preventDefault

Upvotes: 1

netiul
netiul

Reputation: 2769

$('.view_details').click(function(e) {
   e.preventDefault();
   //do your stuff
});

Upvotes: 1

Seth
Seth

Reputation: 6260

This is likely related to the fact that your View Details button is an anchor with a # as the href value.

You can stop this by adding:

return false;

or using a preventDefault() call.

jQuery:

$('.view_details').on('click', function(event) {

    // Your Code
    event.preventDefault();
    // or
    return false;

});

This will stop the link from sending you to the top of the page.

Upvotes: 3

CambridgeMike
CambridgeMike

Reputation: 4622

I'm guessing you have an anchor tag that they can click on?

and that anchor tag links to "#"?

If so, try adding onclick="return false;" to that tag

<a href='#' class='view_details' onclick='return false;'>View details</a>

Upvotes: 2

xkeshav
xkeshav

Reputation: 54084

use <a href="javascript:void(0)"> instead of #

Upvotes: 3

Related Questions