How can I prevent my anchors jumping my screen around so much?

Andy picture Andy · Jul 27, 2012 · Viewed 8.1k times · Source

I decided to try to create a tabbed menu using just CSS and HTML. Using the :target pseudo-class to show the appropriate div, I've implemented it, only it jumps around a bit too much to be user friendly:

http://brad.sebdengroup.com/newodynsite/stockman.php#StockControl

Is there anyway I can fix this? Initially, I wanted to stay away from JavaScript, but I will happily add some if it fixes this.

Note: I know I can rebuild a new tabbed menu using jQuery/some fancy library but if possible, I'd rather fix this.

Answer

Undefined picture Undefined · Jul 27, 2012

Its because your using a hash value in your anchors. These cause it to jump to a div with the id specified by the hash.

To sort this you can use jQuery to stop the jumping by using .preventDefault();

You would use this by giving every anchor that jumps a class of prevent and then using jQuery to stop the jumping. Of course, you can change this selector dependant upon your html structure.

$(".prevent").click(function(e) { //Note the e for event
  e.preventDefault();
});

Edit without jQuery

After cursing not having jQuery to work with I have attempted to put together a pure js solution. You will need to check this to make sure it works on your page.

Here is the jsfiddle example.

What I have done is found all anchors on the page and then added return false into their onclick attribute. If this was to go on your live site you will need to further select the anchors, see this example and explanation:

I have also added a class to anchors you do not want to jump. To use this you will need to add a class of "menuControl" to any anchor you want to stop jumping.

Below is my JavaScript incase the jsfiddle link is broken. Just to mention but you will need to control the navigation of these tabs using JavaScript now, as using return false will stop the navigation.

var anchors = document.getElementsByTagName("a");

for(var i = 0; i < anchors.length; i++) {
    if ( anchors[i].className == "menuControl" ) {
        anchors[i].setAttribute("onclick", "return false");
    }
} ​