depending on which container I click, I would like to add a class to the equal box. So if I click on the first container -> add class to first box.
In my script I have to write it for each container and duplicate it.. - but I guess there is a way to make it easier? At the end there will be around 100 entries
This HTML:
<div id="row">
<div >
<div >A</div>
</div>
<div >
<div >B</div>
</div>
<div >
<div >C</div>
</div>
<div >
<div >D</div>
</div>
</div>
<div id="row-second">
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
</div>
This Script:
$("#row .container:nth-child(1) div.info").on("click", function() {
$("#row-second div.box:nth-child(1)").addClass("show");
});
$("#row .container:nth-child(2) div.info").on("click", function() {
$("#row-second div.box:nth-child(2)").addClass("show");
});
....
CodePudding user response:
You can use this to identify the element/div being clicked.
You can then use .index() to get where it is within its parent - there's a small issue here in that you have row > container > info so each info index will be 0 - so you need to get the .container's index.
Then use $("#row-second div.box").eq(idx) to find the corresponding box
Added $(".show").removeClass("show"); as the name "show" implies you want to show just the one being clicked and hide the others; obviously remove this if your use-case is to leave them shown.
Updated snippet:
$("#row .container div.info").on("click", function() {
var idx = $(this).closest(".container").index();
$(".show").removeClass("show");
$("#row-second div.box").eq(idx).addClass("show");
})
#row div { cursor: pointer; }
#row-second div { display:none; }
#row-second div.show { display:block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="row">
<div >
<div >A</div>
</div>
<div >
<div >B</div>
</div>
<div >
<div >C</div>
</div>
<div >
<div >D</div>
</div>
</div>
<hr>
<div id="row-second">
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
</div>
CodePudding user response:
Something like this should work:
$("#row").on("click", ".container div.info", function() {
const index = $(this).closest(".container").prevAll(".container").length;
$(`#row-second div.box:nth-child(${index 1})`).toggleClass("show");
});
#row {
display: flex;
}
.container {
margin: 5px;
padding: 5px;
outline: 1px dotted black;
cursor: pointer;
flex: 1 0 2em;
}
#row-second {
display: flex;
}
#row-second .box {
margin: 5px;
padding: 5px;
outline: 1px dotted black;
flex: 1 0 2em;
}
.show {
background-color: #0a0;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="row">
<div >
<div >A</div>
</div>
<div >
<div >B</div>
</div>
<div >
<div >C</div>
</div>
<div >
<div >D</div>
</div>
</div>
<div id="row-second">
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
</div>
