Reputation: 794
Using the following code, when a menu item is clicked it loads the content from an external html file. When I click through each menu item, the content from each external html file stays on the page. How can I make it so that as I click through, only the content from the clicked menu item is displayed?
<script type="text/javascript">
$(function(){
$("#accordion1").click(function(evt){
$("#course1").load("course1.html")
evt.preventDefault();
})
$("#accordion2").click(function(evt){
$("#course2").load("course2.html")
evt.preventDefault();
})
$("#accordion3").click(function(evt){
$("#course3").load("course3.html")
evt.preventDefault();
})
})
</script>
<div id="content">
<div id="course1">
</div>
<div id="course2">
</div>
<div id="course3">
</div>
</div>
Upvotes: 0
Views: 99
Reputation: 16373
You could simply empty the other elements, using $().empty()
, but I think a better solution would be to toggle visibility, using something like $().toggleClass('hiddenCourse')
and a display:none
CSS associated with this class.
Also, as fetching files each time would be really slow responsive, and network demanding, you should consider remembering which files have already been fetched and included into the DOM.
An alternative would be to have all content ready at page load, so the only remaining task would be the visibility toggling. It depends on a a lot of parameters: if the sum of content is big (files' size and number), if you prefer a lightspeed responsive app in trade of a slower startup, the number of sections the visitor is likely to open, and so on.
Upvotes: 1
Reputation: 13615
You could either:
Upvotes: 0
Reputation: 270599
If I understand, you want to clear out the other <div>
s:
<script type="text/javascript">
$(function(){
$("#accordion1").click(function(evt){
$("#course1").load("course1.html");
$("#course2").empty();
$("#course3").empty();
evt.preventDefault();
})
$("#accordion2").click(function(evt){
$("#course2").load("course2.html");
$("#course1").empty();
$("#course3").empty();
evt.preventDefault();
})
$("#accordion3").click(function(evt){
$("#course3").load("course3.html");
$("#course1").empty();
$("#course2").empty();
evt.preventDefault();
})
})
</script>
Upvotes: 0
Reputation: 17263
It looks like you want something like the Accordion UI effect
Have a look here, that way you only need to load the content once. http://docs.jquery.com/UI/API/1.8/Accordion
Also calling $('#id').empty();
will remove content.
Upvotes: 0