B.Glock B.Glock - 5 months ago 12
jQuery Question

Show nth:div 1, when i click nth: anchor

Good Evening helpful people of stackoverflow,

I want to hide the **clicked **

.project-tile-normal
and show the appropriate description div
.detail-tile
.

I read through some articles regarding my question, but i run into a logical brickwall in my head. Needlessly to say, i'm a beginner in jquery and maybe there is a better way to do that, i just didn't find it.

Here's what i found so far as "answers":

Hide Children, Show nth Child - the closest answer to my question

Show and Hide Several Links - this solution makes my head dizzy

My HTML consists of two rows of divs, similar to that simplified representation:

<div class="wrapper">
<div class=".project-tile-normal">some pictures</div>
<div class=".project-tile-normal"></div>
<div class=".project-tile-normal"></div>

<div class=".detail-tile">description</div>
<div class=".detail-tile"></div>
<div class=".detail-tile"></div>
</div>


This is what i have so far coded:

JQUERY

$(document).ready(function(){
$('.project-tile-normal').on("click", function() {
if( $(this).hasClass("active") ) {
$(this).fadeOut(150);
} else {
var itemid = '#div' + $(this).attr('target'); // my own try to get the Element of the divs.
console.log(itemid);
$(this).addClass("active");
$(".detail-tile").removeClass("hidden");
}
});

$('button').on("click", function(){
$(".detail-tile").addClass("hidden");
$(".project-tile-normal").fadeIn(150);
$(".project-tile-normal").removeClass("active");
});
});//document ready


Should i put all the Items in an array and then count it out? Thanks for your help in advance.

Answer

Firstly note that your class attributes in the HTML should not contain any . characters.

With regard to the JS, you can link elements by index by retrieving the index() from the clicked element then selecting the matching required element using eq(), something like this:

$('.project-tile-normal').click(function() {
    var index = $(this).index();
    $('.detail-tile').hide().eq(index).show();
});

Working example

Comments