Reputation: 47
I want to load the contents of various <li>
into a single <div>
when each <li>
is clicked. Each time a new <li>
is clicked, it should then unload the current contents and load its contents into the <div>
.
<div id="main-content">Text that will be replaced</div>
<li class="title">1 - This will replace "main-content" text when clicked</li>
<li class="title">2 - This will replace "main-content" text when clicked</li>
<li class="title">3 - This will replace "main-content" text when clicked</li>
<li class="title">4 - This will replace "main-content" text when clicked</li>
How can I make this work with jQuery? Seems like it shouldn't be too difficult, but I'm a bit of a jQuery neophyte.
Upvotes: 1
Views: 3649
Reputation: 56501
Yes you're right. This is easy in jQuery
.
click
) and event handler attachments(.on()
). .text()
and .html()
)$('.title').on('click', function () {
$('#main-content').text($(this).text());
});
Check this JSFiddle
Update: from your comments
<html>
<head></head>
<body>
<div id="main-content">Text that will be replaced</div>
<li class="title">1 - This will replace "main-content" text when clicked</li>
<li class="title">2 - This will replace "main-content" text when clicked</li>
<li class="title">3 - This will replace "main-content" text when clicked</li>
<li class="title">4 - This will replace "main-content" text when clicked</li>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.title').on('click', function () {
$('#main-content').text($(this).text());
});
});
</script>
</body>
</html>
Try this as a separate file. My concern is that you're not properly importing the jQuery
.
Upvotes: 1
Reputation: 27364
You can do this as below.
$('.title').on('click',function(){
$('#main-content').html($(this).html());
});
Upvotes: 1
Reputation: 219
$('li.title').click(function(){
$('div#main-content').text(this.text());
})
or use 'html' method instead of 'text' if you want to move also html content
Upvotes: 0