Reputation: 440
I'd like to hide and show a div
(jQuery toggle()
). This is an example of my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("a").click(function() {
var myelement = $(this).attr("href");
$(myelement).slideToggle("slow");
$(".toggle:visible").not(myelement).hide(500);
});
</script>
<h2><a href="#box1"> Programming</a></h2>
<div id="box1" class = "block-content" style="display:none">
box 1
</div>
<h2><a href="#box2"> software</a></h2>
<div id="box2" class = "block-content" style="display:none">
box 2
</div>
It doesn't work and Firebug doesn't show me an error message.
Can you help me ?
Upvotes: 0
Views: 93
Reputation: 71
$(".toggle:visible").not(myelement).hide(500);
replace ".toggle:visible" with "div"
Upvotes: 1
Reputation: 28114
When the script runs, the a tags are not yet present on the page!
Put your script below the html elements, or use document ready or equivalent to postpone the script execution.
Upvotes: 1
Reputation: 34107
Demo: http://jsfiddle.net/xyzpq44x/
preventDefault
you want to prevent default behaviour of a
tag http://api.jquery.com/event.preventdefault/rest should help :)
try this
$("a").click(function (e) {
e.preventDefault();
var myelement = $(this).attr("href")
$(myelement).slideToggle("slow");
$(".toggle:visible").not(myelement).hide(500);
});
Upvotes: 1