3
$('.box').click(function(){
    $(this).find('p').toggle(
        function () {
            $(this).css({"color" : "red"});
        },
        function () {
            $(this).css({"color" : "black"});
        }
    );
});

if i execute this script the 'p' color will change if i click on the 'p' not on the .box class why ? And how to i make it so that 'p' color changes when i click on the .box div

John Hartsock
  • 85,422
  • 23
  • 131
  • 146
andrei
  • 8,252
  • 14
  • 51
  • 66
  • Could you clean that code up so it's legible? It's all over the place. (Edit: Never mind, John Hartsock did it for you. But please read the editing help: http://stackoverflow.com/editing-help) – T.J. Crowder Jun 10 '10 at 13:43
  • is your P inside the .box div, if yes that can be because of event propogation – sushil bharwani Jun 10 '10 at 13:46

2 Answers2

7

.toggle() assigns event handlers to the click event, what you want is this:

$('.box').toggle(function(){
    $('p', this).css({"color" : "red"});
},  function () {
    $('p', this).css({"color" : "black"});
});

Every time you wrap a new function, this refers to the element you're dealing with (at least, for this example, see more about how closures work here), so at first it's the .box selector match, then it's each p inside, you want to assign a click toggle on .box to switch p's color, so you use a .toggle() on .box directly.

Community
  • 1
  • 1
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
1

Another option would be to simply assign the colors in classes, and use .toggleClass().

Give the p elements the black class initially, then toggle the red class.

CSS

    .black { color: black; }
    .red { color: red; }

jQuery

$('.box').click(function(){
        $(this).find('p').toggleClass('red');
});
user113716
  • 318,772
  • 63
  • 451
  • 440