1

Basically I'm trying to change background-color of some JQuery added divs of class="cell" into a parent div of class="grid". So the "cell" class isn't defined in the original index.html

so it works when i write the code like this:

$(document).ready(function() {
    var clr = "red";
    $('.cell').mouseenter(function() { 
        $(this).css('background-color', clr);
    });
});

but it doesn't when i define a function like:

$(document).ready(function() {
    function fillCell(clr){
        $(this).css('background-color', clr);
    }

    $('.cell').mouseenter(function() { 
        alert(clr);     //added for test 
        fillCell("red");
    });

});

please note that the alert() is triggered when hovering and responds with "red".

Ozilyo
  • 11
  • 4

2 Answers2

-1

this only works in the context of any function being passed in as a parameter(anonymous or your defined function). What you could do is just pass this as a parameter to the function in your case since you need it to do additional things and it would work the way you want it to.

$(document).ready(function() {
    function fillCell(clr, o){
        $(o).css('background-color', clr);
    }

    $('.cell').mouseenter(function() { 
        alert(clr);     //added for test 
        fillCell("red", this);
    });
});
Jacob Morrison
  • 570
  • 1
  • 8
  • 18
-1

Do this instead.

fillCell.call(this, "red");

The mouseEnter event handler has its context (this) set to the element that the event was triggered on. However, by extracting your function definition to the outside of the event handler, you're losing the this context. .call() lets you override that context. Read more here.

Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
Merott
  • 6,527
  • 6
  • 32
  • 50
  • I'm sorry about the initial errors. I've learnt not to type answers with my phone again :) – Merott Nov 19 '15 at 21:27
  • Thank you very much, looks like your method is the best practice – Ozilyo Nov 20 '15 at 21:04
  • @Ozilyo Thanks for accepting as the answer. I'd appreciate an upvote, to counter for the downvote that I received because of the bad formatting I did on my phone :) – Merott Nov 22 '15 at 13:06
  • I would love to, but I cant cuz I don't have enough reputation :( sorry. – Ozilyo Nov 22 '15 at 15:51