1

Function current_child will execute without html li.first is being clicked becouse of a param. How could i send a param like event.target to current_child when its clicked. At the moment it executes when page is being loaded. Skipping the param like $(document).on("click", "li.first", current_child) and the function will wait to be executed untill the html object is being clicked.

var toggle = false;
function current_child(value){
    if(value == 1){
        alert("Hello");
    }
    event.preventDefault();
}


$(document).on("click", "li.first", current_child(1));
Nicco
  • 286
  • 1
  • 2
  • 15

3 Answers3

1

Use bind instead of directly calling your handler:

$(document).on("click", "li.first", current_child.bind(null, 1));
RienNeVaPlu͢s
  • 7,442
  • 6
  • 43
  • 77
1

You can use lexical scoping of Javascript variables and return inner function

function current_child(value){
    return function (event) {
        if(value == 1){
            alert("Hello");
        }
        event.preventDefault();
    };
}

$(document).on("click", "li.first", current_child(1));

its called closure

Community
  • 1
  • 1
ertrzyiks
  • 386
  • 1
  • 6
1

You can also wrap it in an anonymous function:

$(document).on("click", "li.first", function() { current_child(1); });
Rhumborl
  • 16,349
  • 4
  • 39
  • 45
  • I would rather avoid anonymous functions becouse it can become clumpsy if have to use it multiple times. – Nicco Jan 14 '15 at 15:08