0

Given HTML such as

<div class="tpl grey">Hosts:
    <p>Hi !</p>
    <p>How are you ?</p>
    <p>What ever.</p>
    <a href="./~">An other child & element type !</a>
</div>

How to make that a click on a child element toggle the class="grey" of the closest parent .tpl element ?


The following code fails :

//Action to do on parent $(".tpl") 
var switch1 = function () {
    $(this).closest(".tpl").toggleClass("blue grey");
}

// On() click event
$(document).ready(function() {
        $(".tpl").on("click", "p", switch1() );
});

Fiddle: http://jsfiddle.net/MRcCy/1

Hugolpz
  • 17,296
  • 26
  • 100
  • 187
  • `$(".tpl").on("click", "*", switch1() )` should be better so it works on all child element (*) – Hugolpz Feb 22 '14 at 18:59
  • 1
    Change `$(".tpl").on("click", "p", switch1() );` to `$(".tpl").on("click", "p", switch1 );` http://jsfiddle.net/j08691/MRcCy/2/ – j08691 Feb 22 '14 at 18:59
  • 1
    If you have code such as `foo(bar())`, then `bar` is executed *first* and it's return value is passed to `foo`. Arguments are always evaluated first. – Felix Kling Feb 22 '14 at 19:02
  • @FelixKling: Oh, true, that explain it thanks. – Hugolpz Feb 22 '14 at 20:13

2 Answers2

1

If you just want to toggle the closest .tpl (even though i only see one) try this

$(document).ready(function() { $(".tpl p").click(function(){ $(this).closest('.tpl').toggleClass('grey'); }); });

1

Check this fiddle

$(document).ready(function() {
    $(".tpl").click(function(){
        $('.tpl').toggleClass('grey blue');
    });
});
Bhavik
  • 4,836
  • 3
  • 30
  • 45