Why is this code not targeting the correct selector

This function should change the background color of the object pressed

function colorMe(){ $(this).css('background-color', 'red'); } 

I call it that

 $('.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. Therefore, I can not use only $('.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 not working }); 

but this does not affect the div. I think he lost control of the case. I need to pass it on and how?

+6
javascript jquery
source share
3 answers
 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 in a jQuery object like you here,

 $(this).colorMe() 

you will need to create 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 can do

 $(".a_class").colorMe(); $(".a_class").unColorMe(); 
+5
source share

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 the best name!)

 .my-red-class { background-color: red; } 

And you can also easily remove css:

 function unColorMe(element){ element.removeClass('my-red-class'); } 
+3
source share
 function colorMe(){ $(this).css('color', 'red'); } 

by calling ()

 $('.colorme').click(function(){ alert('something happens first, then colorMe is called'); colorMe.call(this); }); 
+1
source share

All Articles