i using this code, here:
But i want to copy those two buttons under the divs BUT i don't know how to change code to achieve this:
- when i click on button a -> button is active, when i click on button b -> button b is active
i want my copied buttons under div to be active aswell :)
When i click upper button b and it shows on red i want the same on down button b and same thing with button a (no matter if i click upper or down button) :)
Maybe you will understand my vision and can help me, i hope so - thanks :D
CodePudding user response:
You can do this by adding a new CSS class to the buttons. The "A" buttons need the same class and the "B" buttons need the same class. In your javascript you can switch which classes are active based on the class the current target has.
// set content on click
$('.button').click(function(e) {
e.preventDefault();
setContent($(this));
});
// set content on load
$('.button.active').length && setContent($('.button.active'));
function setContent($el) {
$('.button').removeClass('active');
$('.container').hide();
if ($el.hasClass('a-button')){
$('.a-button').addClass('active');
} else {
$('.b-button').addClass('active');
}
$($el.data('rel')).show();
}
.container {
display: none;
}
.button.active {
color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<ul>
<li><a data-rel="#content-a" href="#">a button</a></li>
<li><a data-rel="#content-b" href="#">b button</a></li>
</ul>
<div >
<div id="content-a">
AAA
</div>
<div id="content-b">
BBB
</div>
</div>
<ul>
<li><a data-rel="#content-a" href="#">a button</a></li>
<li><a data-rel="#content-b" href="#">b button</a></li>
</ul>
</div>
CodePudding user response:
This can be done by adding another data attribute.
<div >
<ul>
<li><a data-rel="#content-a" data-group="a" href="#">a button</a></li>
<li><a data-rel="#content-b" data-group="b" href="#">b button</a></li>
</ul>
<div >
<div id="content-a">
AAA
</div>
<div id="content-b">
BBB
</div>
</div>
<ul>
<li><a data-rel="#content-a" data-group="a" href="#">a button</a></li>
<li><a data-rel="#content-b" data-group="b" href="#">b button</a></li>
</ul>
</div>
// set content on click
$('.button').click(function(e) {
e.preventDefault();
setContent($(this));
});
// set content on load
$('.button.active').length && setContent($('.button.active'));
function setContent($el) {
$('.button').removeClass('active');
$('.container').hide();
$el.addClass('active');
$('a[data-group="' $el.data('group') '"]').addClass('active');
$($el.data('rel')).show();
}
Note: You could remove the data-rel attribute and use the one data attribute to dictate everything.