3

Here is my code, which does not show any error, but don't go to href location either. Code works when I change href to "www.google.com". Why it does not work for same page link?

<form>
<a href="#DivIdToScroll">
   <div id="btnLink" onClick="generateReport();"> Generate </div>
</a>
</form>

<script>
function generateReport()
{
    window.location.href = '#DivIdToScroll';
}
</script>
SaidbakR
  • 11,955
  • 16
  • 89
  • 173

3 Answers3

3

I prepared a code snippet from the code you provided. I just made a long container, and inserted a div with the Id "DivIdToScroll" in the lower part. It seems to be working alright. You may have used a class instead of Id. Hope it helps.

 function generateReport() {
   window.location.href = '#DivIdToScroll';
 }
.longContainer {
  height: 1000px;
  background: #eee;
}
.justTakingSpace {
  height: 600px;
  margin: 2px;
  background: #ddd;
}
<div class="longContainer">
  <form>
    <a href="#DivIdToScroll">
      <div id="btnLink" onClick="generateReport();">Generate</div>
    </a>
  </form>

  <div class="justTakingSpace"></div>

  <div id="DivIdToScroll">Oh you're here at "#DivIdToScroll". hello hello.</div>
</div>
thereisnospoon
  • 255
  • 2
  • 8
  • Thanks working now. Div was hidden before i add window.location.href = '#DivIdToScroll'; in function. That was the reason. when I place it at end of function, Its working good. – Deepika Karande Dec 03 '15 at 06:58
2

You can try this set of code, it has animation too.

<div id="DivIdToScroll">Go to link</div>

Here jquery code

$("#DivIdToScroll").click(function(){

$('html, body').animate({
        scrollTop: $("#scroll_div").offset().top
    }, 1000);
});

and here is the content div

<div id="scroll_div">Content</div>
Adas
  • 309
  • 1
  • 16
2

Without Animation

function generateReport() {
  window.location.href = '#DivIdToScroll';
}
<form>

  <a href="#DivIdToScroll">
    <div id="btnLink" onClick="generateReport();"> Generate </div>
  </a>

  <div style="height:500px">&nbsp;</div>

  <div id="DivIdToScroll">Go to link</div>

  <div style="height:500px">&nbsp;</div>
  
</form>

With Animation

function generateReport() {
  $('html, body').animate({
    scrollTop: $("#DivIdToScroll").offset().top
  }, 1000);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>

  <a href="#DivIdToScroll">
    <div id="btnLink" onClick="generateReport();"> Generate </div>
  </a>

  <div style="height:500px">&nbsp;</div>

  <div id="DivIdToScroll">Go to link</div>

  <div style="height:500px">&nbsp;</div>

</form>
ankitkanojia
  • 2,872
  • 4
  • 18
  • 30