Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript help, toggle text keeps jumping back to top of page

I hope someone can help with this issue, I've tried many scripts and workarounds, but can't get this simple thing to work. As the title has it, how can I make my text NOT jump to the top of the page. Here is the code:

<script type="text/javascript">
function toggleVisibility() {
  document.getElementById("toggleMe").style.display = "";
  if(document.getElementById("toggleMe").style.visibility == "hidden" ) {
    document.getElementById("toggleMe").style.visibility = "visible";
  }
  else {
  document.getElementById("toggleMe").style.visibility = "hidden";
   ev.preventDefault();
    return false;

  }
}
</script>



 <a href="#" onclick="toggleVisibility();">Click to toggle visibility.</a></p>
 
<div id="toggleMe" style="visibility: hidden;"> Something to Hide and show.

Display collapses it's layout while visibility will keep it's layout.

All in the same html file. I read what outhers did and I tried the

ev.preventDefault(); return false;

code at the end of the function, but nothing.

like image 773
Ollie Avatar asked Feb 25 '23 02:02

Ollie


1 Answers

Change the href attribute in the A tag to: javascript:; instead of #

So use this to create your javascript enabled anchor:

<a href="javascript:;">

added (background info):

The # character indicates a bookmark. By omitting the name of the bookmark e.g. #bottom the browser considers the bookmark as 'top of the page' thus scrolling to the top. Your problem does not have to do anything with bookmarks, however using # to define an empty link for a javascript enabling anchor (A) tags is not the way to go. You should use: javascript:; or javascript:void(0); to indicate that this is not a navigation anchor.

like image 184
ReFocus Avatar answered Mar 03 '23 21:03

ReFocus