Joseph
Joseph

Reputation: 1744

Prevent jquery show/hide div to goto top of page

The following script works for me to show a certain div when clicking a link and hiding any other that might be shown (so that only one is shown at a time). But the script also goes to top when clicking a link. How can I aboid that.

Code:

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){

$('a').click(function () {
var divname= this.name;
$("#"+divname).show("slow").siblings().hide("slow");
});

});
</script>
</head>
<body>


<ul>
<li><a href="#" name="div1" >Show div1</a></li>
<li><a href="#" name="div2" >Show div2</a></li>
<li><a href="#" name="div3" >Show div3</a></li>
<li><a href="#" name="div4" >Show div4</a></li>
</ul>

<div>

<div id="div1" style="display:none">
This is div1
</div>

<div id="div2" style="display:none">
This is div2
</div>

<div id="div3" style="display:none">
This is div3
</div>

<div id="div4" style="display:none">
This is div4
</div>

</div>

</body>
</html> 

Upvotes: 1

Views: 3309

Answers (6)

user2787009
user2787009

Reputation: 11

Use event.preventDefault(); after $('a').click(function ()

It will be something like:

<script>
$(document).ready(function(){
 $('a').click(function () {
 event.preventDefault();
 var divname= this.name;
 $("#"+divname).show("slow").siblings().hide("slow");
 });
});
</script>

Upvotes: 0

wcndave
wcndave

Reputation: 314

I have not found a solution to this, and you must completely avoid the return false as this breaks accessibility.

When you click the link, the focus is on the target div, so if you use keyboard you will navigate through the div you have selected.

Using return false means the focus is at the top of the page, so the user would have to tab through the entire page every time, to get to where they want.

I would post this as a reply to other answers, however I cannot see any way to do that.

Upvotes: 0

gion_13
gion_13

Reputation: 41533

use both e.preventDefault() and return false; for safety

Upvotes: 1

Dormouse
Dormouse

Reputation: 5198

$('a').click(function (e) {
    e.preventDefault();

    var divname= this.name;
    $("#"+divname).show("slow").siblings().hide("slow");
});

Upvotes: 2

AEMLoviji
AEMLoviji

Reputation: 3257

look here jQuery event.preventDefault

Upvotes: 1

nfechner
nfechner

Reputation: 17545

The reason for that is the # in your hrefs. Just use return false; as the last statement in your click handler to prevent that.

Upvotes: 3

Related Questions