Reputation: 430
To be brief, i have two buttons that have the same class, one of them have an attribute data-toggle='modal'
. I use this attribute to detect the button.
I need to change the color of the button which does not have an attribute data-toggle
, I can't target it by using the className, because they both have the same.
In the js click function, I use a ternary condition to say: if the button has an attribute 'data-toggle
' then do nothing, else removeClass btn--ghost
and addClass btn--plain
. But it doesn't work.
PS: the btn--plain
is the class name used to give the button a bgcolor instead of btn--ghost
.
This is the js :
if ($('.o-block-global .btn--link').length) {
$('.btn--primary').on("click", function (e) {
console.log("iiiiii", $(this));
$(this).attr("data-toggle" ? "" : $(this).removeClass("btn--ghost").addClass("btn--plain"));
});
}
This is the HTML :
<div class="o-block-global__links link_choice ">
<button type="button" class="btn btn--ghost btn--primary">
OUI
</button>
<button type="button" class="btn btn--ghost btn--primary" data-toggle="modal" data-target="#modalChoice2">
NON
</button>
</div>
Upvotes: 2
Views: 377
Reputation: 28522
You can check if the attr
value is undefined
or not using (typeof $(this).attr("data-toggle")) !== 'undefined'
Demo Code :
$('.btn--primary').on("click", function(e) {
//check if the attr type is not undefined
(typeof $(this).attr("data-toggle")) !== 'undefined' ? "" : $(this).removeClass("btn--ghost").addClass("btn--plain");
});
.btn--ghost {
color: red;
}
.btn--plain {
color: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="o-block-global__links link_choice ">
<button type="button" class="btn btn--ghost btn--primary">
OUI
</button>
<button type="button" class="btn btn--ghost btn--primary" data-toggle="modal" data-target="#modalChoice2">
NON
</button>
Upvotes: 1
Reputation:
To do that you use the :active selector
. HTML:
<button>Click Me!</button>
button{
background:green;
}
button:hover{
background:lightgreen;
}
button:active{
background:red;
}
Upvotes: 0