IronWilliamCash IronWilliamCash - 4 months ago 25
CSS Question

javascript toggle function causes page to scroll to the top

I have a small problem with a webpage returning back to the top of the page after a javascript function is executed.

Basically, I have a small javascript function that toggles the visibility of a div by changing it's display style. the code is the following:

<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if( == 'block') = 'none';
else = 'block';

I then call this with a link that looks like this:

<a href="#" onclick="toggle_visibility('001');" class="expand">[+/-] Hide/Show Info</a>

and the div looks something like this:

<div id="001" style="display:none;">
hello world

This works just fine. But when I click on my "expand/hide" link to toggle the visibility of the div, the page always returns to the top, so I have to scroll back down to the bottom every time.

I have tried adding the the following changes at the end of my javascript function, but neither of them works:

window.location = 'test.php#' + id; //where test.php is my current page



Any help would be appreciated in fixing this issue


It is recommended to not overload a link, but use a span instead:

Live Demo

.expand { cursor:pointer; }

<span data-div="x001" 
 class="expand">[+/-] Hide/Show Info</a> 

Also I strongly recommend to

  • not use numerical IDs
  • not use inline event handlers


window.onload=function() {
  var links = document.querySelectorAll(".expand");
  for (var i=0;i<links.length;i++) {
    links[i].onclick=function(e) {
      var ele = document.getElementById(this.getAttribute("data-div"));
      if (ele) = == "block"?"none":"block";


<div id="x001">...</div>

With a link, you can use a page as href to tell the user to enable JS or suffer the consequences :)

<a href="pleaseenablejs.html" data-div="x001" 
 class="expand">[+/-] Hide/Show Info</a> 

To fix your code you need to return false. In newer browsers, use event.preventDefault

function toggle_visibility(id) {
   var elm = document.getElementById(id); = == "block"?"none":"block";
   return false;


<a href="#" onclick="return toggle_visibility('001');" 
 class="expand">[+/-] Hide/Show Info</a>