I’m trying to build a function where when a link is clicked (all have the same class), a class is toggled on another element.
Example: if I click on link 1 red should get the class active. If I click on link 2, pink should get the class active and not the others and so on. My javascript knowledge is limited and I managed to give the link an active class but not the respective elements that I want to focus.
$(".trigger").click(function(){
$('.trigger').removeClass('checked')
$(this).addClass('checked')
})
.main{
position: relative;
width: 500px;
height: 500px;
}
.basic{
width: 300px;
height: 300px;
position: absolute;
right: 0;
}
.red {
background-color: red;
}
.pink {
background-color: pink;
}
.blue{
background-color: blue;
}
.green {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="trigger">Link 1</a>
<a href="#" class="trigger">Link 2</a>
<a href="#" class="trigger">Link 3</a>
<a href="#" class="trigger">Link 4</a>
<div class="main">
<div class="red basic"></div>
<div class="pink basic"></div>
<div class="blue basic"></div>
<div class="green basic"></div>
</div>
3
Answers
try below,
The
position: absolute
on yourbasic
class is stacking the children on top of each other so setting any of them toactive
will cause no visual change so I’ve removed that property so you can see each element. Obviously you can style your elements as you wish.I’ve set up a custom attribute that lets your code know what element to apply the style (I’ve called it
data-target-class
). I’ve use jQuery’s attr method to get that value in to a variable. I’ve then used jQuery’s child selector to pick out all the children and remove the active class. I’ve used the same selector again to target the specific element you want and add theactive
class to that.Finally I’ve created an
active
class that puts a box shadow around the element so you can see what’s ‘active’.Hope this explains everything. If not pop a comment in and I’ll see how I can make it clearer for you.