Naju
Naju

Reputation: 1541

Change the div content according to link selection

Here I have listed my div details.I want to know how to change the content of main div by using the link and load the child div in the main div.

link 1 : link 2: link 3 :link 4

<div id="main">
    <div>diplay1</div>
    <div>diplay2</div>
    <div>diplay3</div>
    <div>diplay4</div>
</div>

Please advice me.

Upvotes: 0

Views: 222

Answers (3)

Spokey
Spokey

Reputation: 10994

Using this format

<div id="main">
    <div>diplay1</div>
    <div>diplay2</div>
    <div>diplay3</div>
    <div>diplay4<div>ok</div></div>
</div>

<div>
  <a href='javascript:;' class='link'>1</a>
  <a href='javascript:;' class='link'>2</a>
  <a href='javascript:;' class='link'>3</a>
  <a href='javascript:;' class='link'>4</a>
</div>

Then with a small script

$('.link').click(function(){
   $('#main > div').hide().eq($(this).index()).show();
});

Fiddle Example

Upvotes: 2

Faisal Sayed
Faisal Sayed

Reputation: 793

You will need to use JS / JQuery , CSS and classes to achieve that.

HTML with classes, href, and custom attribute.

<a class="linked" data-link="content1" href="#">Link1</a>
<a class="linked" data-link="content2" href="#">Link2</a>
<a class="linked" data-link="content3" href="#">Link3</a>

<div id="main">
    <div class="content1">diplay1</div>
    <div class="content2">diplay2</div>
    <div class="content3">diplay3</div>
</div>

JQuery code

$('a.linked').on('click', function(e){
    $('div.' + $(this).attr('data-link')).show().siblings().hide();
    /* this will select and show div with class 
       which is in the custom attribute data-link of the clicked link. 
       Then it will select all of its sibling elements 
       i.e. all within this parent and no children if any 
       except the first selected div and will hide them. */
});

CSS styles

#main *{
    display:none;
}

Example Fiddle

Upvotes: 1

HIRA THAKUR
HIRA THAKUR

Reputation: 17757

Working Fiddle!!!

$('#main a').click(function() {
    $('div:not(#main)').hide();
    $($(this).attr('href')).show();
    return false;
});

Upvotes: 1

Related Questions