'Change display property scrolls the page to it's top

I have a problem with changing objects display property with Javascript.

I fill a table from data in a mysql database using php, and for each row it makes a DIV with display:none property as I want, and I have a simple JavaScript function to show/hide the div. Here is css for div :

display:none; /*initially menu item is hidden*/
position: absolute; /*absolute positioning to float*/
background-color:#fff;
width:230px;
min-height:120px;
right:60px;
border:5px solid #ccc;
text-align:right;
direction:rtl;
padding:10px;
border-radius: 10px 10px 10px 10px; 
-moz-border-radius: 10px 10px 10px 10px; 
-webkit-border-radius: 10px 10px 10px 10px; 

and this is the javascript :

function showfield (a) {
    document.getElementById(a).style.display = "block";  
}
function hidefield (a) {
    document.getElementById(a).style.display = "none";  
}

The function works and divs show at the place they must, but the problem is :

when I call the JavaScript function to show, it shows the div but the page scrolls to its top and for seeing the opened div I should scroll down, as my page is a report page it may be a long long page and this is not a good happening at all!

I can't understand why its happens and is there a way to prevent this auto scrolling?



Solution 1:[1]

try this thn....

HTMl

 <a style="text-decoration:none; color:black;" href="#<?php echo("a".$cntr); ?>" onclick="return showfield(<?php echo($cntr); ?>)"><?php echo($cntr); ?></a>

JAVASCRIPT

function showfield(a){
   document.getElementById(a).style.display = "block";
   return false;
}

Solution 2:[2]

Javascript void didn't work for me.

My solution: try giving your button or the href="#mybutton" and id="mybutton". So the page will jump to the button (you can do this for the field too). If you give it href="#" it will jump to the top of the page. And href="" will reload the page and undo the function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bipen
Solution 2 Gerbs