This function is supposed to change the background color of the object being clicked
function colorMe(){
$(this).css('background-color', 'red');
}
I call it like this
$('.colorme').click(colorMe);
and it changes the background of this div
<div class="colorme">Color Me</div>
The problem is that I want to do something else before running colorMe. So I can't use just $('.colorme').click(colorMe);
. What I'm trying to do is something like this
$('.colorme').click(function(){
alert('something happens first, then colorMe is called');
colorMe(); //I call colorMe here..
$(this).colorMe(); //I also tried this, but it's not working
});
but it's not affecting the div. I think it lost track of the div to affect. Do I need to pass it and how?
function colorMe(elt){
$(elt).css('background-color', 'red');
}
$('.colorme').click(function(){
alert('something happens first, then colorMe is called');
colorMe(this); //I call colorMe here..
});
To call a function on a jQuery object like you did here
$(this).colorMe()
you would have to build a plugin (I edited it to add a class)
// css
.red {
background: red;
}
// js
(function($) {
$.fn.extend({
colorMe: function() {
this.addClass("red");
},
unColorMe: function() {
this.removeClass("red");
}
});
})(jQuery);
Then you would be able to do
$(".a_class").colorMe();
$(".a_class").unColorMe();
You should use the .addClass()
method.
function colorMe(element){
element.addClass('my-red-class');
}
$('.colorme').click(function(){
colorMe(this);
});
And in your css file you have a class called 'my-red-class' (use a better name!)
.my-red-class { background-color: red; }
And you can also easily remove the css:
function unColorMe(element){
element.removeClass('my-red-class');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With