user2439212
user2439212

Reputation: 47

Load content from one div into another div on click

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

Answers (3)

Praveen
Praveen

Reputation: 56501

Yes you're right. This is easy in jQuery.

  1. learn about selectors(class and id) .
  2. event handlers(click) and event handler attachments(.on()).
  3. DOM Maniplation(.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

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

You can do this as below.

$('.title').on('click',function(){

    $('#main-content').html($(this).html());

});

Fiddle Demo

Upvotes: 1

bitluni
bitluni

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

Related Questions