Die 20 Die 20 - 1 year ago 49
Javascript Question

Show/Hide div using javascript without page refresh

I have a script that shows /hides multiple independent divs on a page. The problem is that when you click to show a div, no matter where on the page, it will automatically focus on the first div. Is there a way to focus on the div that was displayed?

here is the javascript:

function toggleOptions(e) {
var ele = e;
var text = e.parentElement.querySelector('.toggleOptions')

if(text.style.display == "none") {
//ele.style.display = "none";
text.style.display = "block";
text.innerHTML = "TESTING";
ele.innerHTML = "hide";
}
else {
text.style.display = "none";
//text.innerHTML = "Hide GPS";
ele.innerHTML = "show";
}

return false;
}


here is the html:

<div>
<a href="#" onclick="toggleOptions(this);" style="display:block;">
show
</a>
<div class="toggleOptions" style="display: none">
ITEM 1 OPTIONS
</div>
</div>
<div>
<a href="#" onclick="toggleOptions(this);" style="display:block;">
show
</a>
<div class="toggleOptions" style="display: none">
ITEM 2 OPTIONS
</div>
</div>
<div>
<a href="#" onclick="toggleOptions(this);" style="display:block;">
show
</a>
<div class="toggleOptions" style="display: none">
ITEM 3 OPTIONS
</div>
</div>


here is a jfiddle of the work http://jsfiddle.net/YE6XZ/1/

Answer Source

Give your show links a class, like:

<a class="show" href="#" onclick="toggleOptions(this);" style="display:block;">show</a>

Then add this to your jQuery:

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

The default action for a bookmark anchor (href="#") is to jump to the top of the page. This would prevent that. jsFiddle example

An alternative, jQuery-less method would be to change your onclicks to:

onclick="return toggleOptions(this);"

As you are already returning false. jsFiddle example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download