Reputation: 15
So I'm working on a project an it contains quite a lot of buttons, however is there a way in which when I mouse down on one button, it changes just the button I clicked. I know that I could just add a class to each button, but is there a more efficient way of doing it?
This is the current code which when you click on one button it changes them all.
$("button").mousedown(function() {
$(".button").css("background","-webkit-linear-gradient(black, #333333)");
$(".button").css("background","-o-linear-gradient(black, #333333)");
$(".button").css("background","-moz-linear-gradient(black, #333333)");
$(".button").css("background","linear-gradient(black, #333333)");
});
$("button").mouseup(function() {
$(".button").css("background","-webkit-linear-gradient(#333333, black)");
$(".button").css("background","-o-linear-gradient(#333333, black)");
$(".button").css("background","-moz-linear-gradient(#333333, black)");
$(".button").css("background","linear-gradient(#333333, black)");
});
For example if I had button named 1 could I set it so that the background changed without applying it to all the buttons. Thanks in advance.
Upvotes: 0
Views: 39
Reputation: 1563
You can add and remove classes with your gradients very easily with this code. It will also simplify your code. As well, you will keep all your CSS together;-)
$("button").mousedown(function() {
$(this).removeClass('gradient1').addClass('gradient2');
});
$("button").mouseup(function() {
$(this).removeClass('gradient2').addClass('gradient1');
});
Upvotes: 0
Reputation: 59272
You can use this
as reference to the element being clicked and change that alone.
Example
$(".button").mouseup(function() {
var elem = $(this); // elem contains the clicked element
elem.css("background","-webkit-linear-gradient(#333333, black)");
});
Upvotes: 1