I have a list with 37 links and 37 hidden divs with some text. The counter starts with 3 and ends with 40. What I would like to do is to display a div when I click a link and also hide all the other divs.
Links look like this:
<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 perform this task using jQuery. What I don't know how to do is make a loop and check if any of those links have been clicked.
Something along the line of :
$('a').on('click', function(){
var target = $(this).attr('rel');
$("#"+target).show().siblings("div").hide();
});
Should do the trick.
P.S: your divs have to be in a container for this to work. Fiddle.
Try this:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With