3

I am attaching onclicks to buttons with the function I want to be called when the event happens. When running the page, it goes ahead and executes the function for onclick without clicking.

window.onload=function(){
var recipeCount = 0;
//gets the recipes and puts them in the menu bar #left
//places them in buttons
$.getJSON('recipes.json', function(data) {
       $.each(data.recipe, function(i, f) {
       var yep = "</br> <button type='button' id = '" + f.number + "'>" + f.Name + "</button> </br>";
       $(yep).appendTo("#left");
       recipeCount = recipeCount + 1;


     });//for each recipe

   });//getJSON
//ends recipes to menu
for(var i = 1; i < recipeCount + 1; i++){
    $(i).onclick = clicked(i);
}
$("one").onclick = clicked("one");
};//on load

function clicked(idNum){
    $.getJSON('recipes.json', function(data) {
       $.each(data.recipe, function(i, f) {
       if(idNum == f.number){
        var rec = "</br> <h1> " + f.Name + "</h1> " ;
        $(rec).appendTo("#bigBox");

       }

     });//for each recipe

   });//getJSON
}//clicked

3 Answers 3

2

You are directly calling that clicked() function and causing it to be run, that is why.

The proper syntax is more like:

$('#some-element').click(function(event) {
    // inside click event handler
});

In other words, you would want something like:

$('#some-element').click(function(event) {
    clicked('one');
});

If you're looking for raw JavaScript style, then I believe it would be:

$('#some-element')[0].onclick = functionName;
Sign up to request clarification or add additional context in comments.

Comments

1

First $("one") is not valid, it should be $(".one") if one is a CSS class or $("#one") if one is an ID of any element.

Second you should do this like.

$("#one").click(function(event) {
      clicked("one");
});

Comments

0
clicked(i)   executes the function.

You need to just associate the function pointer to it.

$(i).onclick = clicked(i);

Should be

$('#'+ i).on('click' , function() {
     clicked(i);
});

But this won't work as you seem to be using the value of i in your GETjson. This is a classic closure problem.

for(var i = 1; i < recipeCount + 1; i++){
    $('#'+ i).on('click' , function(num) {
        return function() {
                 clicked(num);
        }
    }(i)  
 );

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.