Reputation: 33
So I have the code:
$(".redd").click(function() {
fillcolor = $(".redd").css("background-color");
});
$(".pink").click(function() {
fillcolor = $(".pink").css("background-color");
});
$(".purple").click(function() {
fillcolor = $(".purple").css("background-color");
});
$(".indigo").click(function() {
fillcolor = $(".indigo").css("background-color");
});
$(".cyan").click(function() {
fillcolor = $(".cyan").css("background-color");
});
$(".blue").click(function() {
fillcolor = $(".blue").css("background-color");
});
$(".yellow").click(function() {
fillcolor = $(".yellow").css("background-color");
});
$(".green").click(function() {
fillcolor = $(".green").css("background-color");
});
$(".orange").click(function() {
fillcolor = $(".orange").css("background-color");
});
$(".black").click(function() {
fillcolor = $(".black").css("background-color");
});
What does this code do? for example $(".redd") is button, and on click it will change the variable 'fillcolor' to the button's background color. How to write this code smarter?
Upvotes: 0
Views: 47
Reputation: 207511
Give them a common class and use $(this) to get the one that was clicked on
$(".color").click(function() {
fillcolor = $(this).css("background-color");
console.log(fillcolor);
});
.green {
background-color: green
}
.blue {
background-color: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="green color" value="green" />
<input type="button" class="blue color" value="blue" />
Upvotes: 3
Reputation: 3118
This is my approach, feel free to add suggestions!
var arry = [".redd", ".pink", ...]
for (var i = 0; i < arry.length; i++)
{
$(arry[i]).click(function() {
fillcolor = $(".purple").css("background-color");
})
}
Upvotes: 1