Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is this code not targeting the right selector

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?

like image 896
zmol Avatar asked Feb 06 '11 07:02

zmol


2 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 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();
like image 118
Robin Avatar answered Sep 28 '22 06:09

Robin


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');
}
like image 32
JK. Avatar answered Sep 28 '22 06:09

JK.