0

I'm using the click/hide function for my questions and answers page. But when I click on the question to show the answer it jumps back up to the top. What do I need to do to get this to stop.

This is my coding:

Script:

<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".sub").hide();
//toggle the componenet with class msg_body
jQuery(".cthrough").click(function()
{
jQuery(this).next(".sub").slideToggle(500);
});});
</script>

CSS:

.cthrough {
    display: inline-block;
    font-size: 15px;
    font-family: 'Anaheim', sans-serif;
    text-transform: uppercase;
    letter-spacing: 0px;
}

.sub {
    display: inline-block;
    font-size: 13px;
    padding-left: 10px;
}

HTML:

<a href="#" class="cthrough">This is my question</a>
<div class="sub">
    This is my answer.
</div>

I have tried converting the a href=# to just a div class but that doesn't make the question clickable. I also tried taking the # out but that didn't help either.

Tessa Wilde
  • 1
  • 1
  • 4
  • Not a duplicate, but relevant to the topic: http://stackoverflow.com/questions/134845/href-attribute-for-javascript-links-or-javascriptvoid0/138233#138233 – James Montagne Oct 23 '13 at 20:15

3 Answers3

4

Keep your href="#" and use jQuery's .preventDefault() to prevent the default action of jumping back to the top.

jQuery(".cthrough").click(function(e) {
    e.preventDefault();  // <-- first line
    jQuery(this).next(".sub").slideToggle(500);
    ...
Sparky
  • 98,165
  • 25
  • 199
  • 285
1

The root cause with # in href. If the URL contains # followed by div name, then user will be landed in that div. This is the browser's default behaviour, In above case when click that URL # is appended to root URL, that's why it takes to top of the page.

To fix this remove href="#" and use style="cursor: pointer" to keep the hand/pointer symbol to that link.

Instead of <a href="#" class="cthrough">This is my question</a> Use <a class="cthrough">This is my question</a> and add the cursor: pointer style to that class(.cthrough).

shaedrich
  • 5,457
  • 3
  • 26
  • 42
Santhosh N
  • 62
  • 4
0

Having the same trouble and e.preventDefault() not working for me if I apply duration to say a slideDown().

Kind of hacky, but this works for me.
The browser freaks out trying to figure the size of the element you're showing during the animation.
So, I show it right away, now the browser knows it's size.
But with low opacity, and then I just fade it in.

// show/hide jobs section
$('.job').hide();

$('a.jobTrigger').click(function(e){
    $('.job').hide();
    $(this).next('.job').show(0, function() {
        
        //animation to stop page jump
        $(this).css('opacity' , '.1');
        $(this).animate({
            opacity: 1
        });
    });
    e.preventDefault(); //keeps hash out of URL
});
greybeard
  • 2,249
  • 8
  • 30
  • 66
flipthekid
  • 121
  • 3