Andrew Dhivakar Andrew Dhivakar - 1 year ago 48
CSS Question

Show/Hide div using href and scroll to displayed div using jquery

I have a jquery function that shows/hides div upon

link click. But everytime the
loads, the page scrolls up to the top instead of the target div. Here is the jquery code and the html layout for
s. The jquery is used to get the id from the clicked link and open target div.

I need the page to scroll to the target div upon click.

so if i click on
then page scrolls to
then when i click on
then page should scroll to

is there a way to edit the jquery to achieve this.

i have tried to use the following inside the click function. but the page does not scroll to the target div.
$('html, body').animate({
scrollTop: $( $(this).attr('#') ).offset().top
}, 500);
return false;

$('a').click(function () {
var divname=;

<a href="#" name="div100" class="btn btn-primary btn-lg" ><font color = "white">item1</font></a>
<a href="#" name="div200" class="btn btn-primary btn-lg" ><font color = "white">item2</font></a>
<a href="#" name="div300" class="btn btn-primary btn-lg" ><font color = "white">item3</font></a>
<a href="#" name="div400" class="btn btn-primary btn-lg" ><font color = "white">item4</font></a>

<div id="div100" style="display:none" align="left">
<li1><a href="#" name="div1" >item1-desc1</a></li1>
<li1><a href="#" name="div2" >item1-desc2</a></li1>
<li1><a href="#" name="div3" >item1-desc3</a></li1>

<div id="div200" style="display:none" align="left">
<li1><a href="#" name="div4" > item2-desc1</a></li1>
<li1><a href="#" name="div5" >item2-desc2</a></li1>
<li1><a href="#" name="div6" >item2-desc3</a></li1>

<div id="div300" style="display:none" align="left">
<li1><a href="#" name="div7" > item3-desc1</a></li1>
<li1><a href="#" name="div8" >item3-desc2</a></li1>
<li1><a href="#" name="div9" >item3-desc3</a></li1>

<div id="div400" style="display:none" align="left">
<li1><a href="#" name="div10" > item4-desc1</a></li1>
<li1><a href="#" name="div11" >item4-desc2</a></li1>
<li1><a href="#" name="div12" >item4-desc3</a></li1>

<div id="div1" style="display:none" align="left">
<!--div1 contents-->
<div id="div2" style="display:none" align="left">
<!--div2 contents-->
<div id="div3" style="display:none" align="left">
<!--div3 contents-->
<div id="div4" style="display:none" align="left">
<!--div4 contents-->
<!--- so on...->

Answer Source

Your try was good, you just put the wrong attr:

$('html, body').animate({
    scrollTop: $( $(this).attr('href') ).offset().top
   }, 500);

And you should add a preventDefault:

$('a').on('click', function(e){
    var divname=;
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top
    }, 500);