Im trying to load select content that is hidden on a page into a content div. To do to this i came across jquery's .load
and .empty
.
It seems to have gone wrong somewhere, but as far as i can see it should work,ideas where im going wrong on this ? And a wider question is .load / .empty the right functions to use for this or is there a simpler way ?
Ive attached my html and Js below, and also created a JSfiddle here : https://jsfiddle.net/poha5cb2/3/
Ive setup the following :
<a id="op-1">Open 1</a><br>
<a id="op-2">Open 2</a><br>
<a id="op-3">Open 3</a><br>
<hr>
<h2>CONTENT</h2>
<div id="content">
</div>
<hr>
<div class="hidden-content-to-be-loaded" style="display: none;">
<div id="one">
<h3>One</h3>
</div>
<div id="two" class="initial-close">
<h3>Two</h3>
</div>
<div id="three" class="initial-close">
<h3>Three</h3>
</div>
</div>
And for the JS ive written
$("#op-1").click(function(){
$("#content").empty();
$("#content").load("#one);
});
$("#op-2").click(function(){
$("#content").empty();
$("#content").load("#two);
});
$("#op-3").click(function(){
$("#content").empty();
$("#content").load("#three);
});
The load()
method is intended to retrieve content from an external URL by making an AJAX request, not to move around the DOM of the current page by selecting existing elements. You also appear to have a syntax error with the missing quotes on the selectors.
As all the content is in the page you don't need to use AJAX at all. If you restructure the HTML slightly and use common classes you can both improve and simplify the code by selecting the related content from the a
by it's matching index and showing it, something like this:
$('.open').click(function(e) {
e.preventDefault();
$('.content').hide().eq($(this).index('.open')).show();
})
.content {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="open">Open 1</a><br>
<a href="#" class="open">Open 2</a><br>
<a href="#" class="open">Open 3</a><br>
<hr>
<h2>CONTENT</h2>
<div id="content-container">
<div class="content">
<h3>One</h3> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam aut, veniam! Eveniet, repudiandae ipsum? Quas ea assumenda, ullam magnam dolores iste neque harum, repudiandae modi distinctio ratione laborum excepturi ad!
</div>
<div class="content">
<h3>Two</h3> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam aut, veniam! Eveniet, repudiandae ipsum? Quas ea assumenda, ullam magnam
</div>
<div class="content">
<h3>Three</h3> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam aut, veniam! Eveniet, repudiandae ipsum? Quas ea assumenda, ullam magnam. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut sint consequatur saepe, quo beatae exercitationem
nostrum quos, illum a inventore fuga dignissimos atque iusto. Quis magnam voluptatibus, ipsum cum assumenda.
</div>
</div>