andrei
andrei

Reputation: 8582

Why does jquery behave like this

$('.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

Upvotes: 3

Views: 91

Answers (2)

user113716
user113716

Reputation: 322492

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');
});

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630419

.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.

Upvotes: 7

Related Questions