Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = '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
</div>

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

and

window.location.hash=id;

Any help would be appreciated in fixing this issue Thanks.

like image 527
IronWilliamCash Avatar asked Dec 14 '22 20:12

IronWilliamCash


1 Answers

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

Live Demo

<style>
.expand { cursor:pointer; }
</style>

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

Also I strongly recommend to

  • not use numerical IDs
  • not use inline event handlers

So

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

using

<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);
   elm.style.display = elm.style.display == "block"?"none":"block";
   return false;
}

using

<a href="#" onclick="return toggle_visibility('001');" 
 class="expand">[+/-] Hide/Show Info</a> 
like image 184
mplungjan Avatar answered Dec 17 '22 11:12

mplungjan