Show one div and hide others when clicking a link

I have a list of 37 links and 37 hidden divs with some text. The counter starts at 3 and ends at 40. What I would like to do is display the div when I click the link, and also hide all other divs.

The links are as follows:

<a href="#" rel="week_3">Week 3</a> <a href="#" rel="week_4">Week 4</a> 

Divs look like this:

 <div id="week_3" style="display: none">[...]</div> <div id="week_4" style="display: none">[...]</div> 

I would like to accomplish this task with jQuery. What I don’t know how to do is create a loop and check if any of these links have been clicked.

+6
source share
6 answers

Something along the line:

 $('a').on('click', function(){ var target = $(this).attr('rel'); $("#"+target).show().siblings("div").hide(); }); 

Gotta do the trick.

PS: your divs must be in the container for this to work. Fiddle

+18
source

Try the following:

HTML:

 <a class="link" href="#" data-rel="content1">Link 3</a> <a class="link" href="#" data-rel="content2">Link 4</a> <a class="link" href="#" data-rel="content3">Link 5</a> <a class="link" href="#" data-rel="content4">Link 6</a> <a class="link" href="#" data-rel="content5">Link 7</a> <div class="content-container"> <div id="content3">This is the test content for part 3</div> <div id="content4">This is the test content for part 4</div> <div id="content5">This is the test content for part 5</div> <div id="content6">This is the test content for part 6</div> <div id="content7">This is the test content for part 7</div> </div> 

CSS

 .content-container { position: relative; width: 400px; height: 400px; } .content-container div { display: none; position: absolute; top: 0; left: 0; right: 0; bottom: 0; } 

Script:

 $(".link").click(function(e) { e.preventDefault(); $('.content-container div').fadeOut('slow'); $('#' + $(this).data('rel')).fadeIn('slow'); }); 

Fiddle

+3
source
 $( "a" ).each(function( index ) { var id = $(this).attr('rel'); $('.data').hide(); $('#'+id).show(); }); 
+1
source

you can check below both jsfiddle . It works fine. do you want like this type?

http://jsfiddle.net/UpuDU/ [Type of accordion]

http://jsfiddle.net/UpuDU/6/ [Type of tab]

+1
source

Do one thing

Give your divs a class so that when you click on links, you can hide this particular class and then show the desired div by clicking on the link

 <div class="abc"></div> <div class="abc"></div> <div class="abc"></div> <a href="#" onClick="$('.abc').hide();"> 
0
source

You have a generic class for all div , for example class='week' . And use the following command to do the necessary:

 $("a[rel^='week']").on('click', function(){ $("div.week").hide(); var targetDiv = $(this).attr('rel'); $("#"+targetDiv).show(); 

});

0
source

Source: https://habr.com/ru/post/951030/


All Articles