0

I'm wondering which is the best way to call a function for each of these element in the code below:

    for (var y=1; y <= 24; y++) {       
    $("#christmasCalendar").append("<div class='span2'><h1><a href='#' data-toggle='tooltip' class='thumbnail' title='Click to add a question for this day'>"+y+"</a></h1></div>")  
    }

Like if I want to call this function:

    $("#createChristmasDayQuiz").click(function () {
    $("#QuizGuideInfo").delay(1000).fadeIn('slow');
    $("div.infoHolder").html('<i class="fa-icon-bullhorn"></i>Select a color theme for your christmas calendar. This can be changed later.').hide().fadeIn('slow');
    $('#createQuiz').modal('show');
    });

I know they can't have the same ID, but still, which is the best solution?

Thanks in advance!

Kim
  • 1,128
  • 6
  • 21
  • 41

2 Answers2

0

You can dynamically create actual DOM elements with jQuery, instead of just inserting them with a string. Then you can do anything you want with them, including binding functions to their click handlers.

E.g.

var myNewElement = $('<div/>').addClass('div-class').appendTo('#christmasCalendar').click(function(e) {
    alert('clicked on new element'); 
});
jraede
  • 6,846
  • 5
  • 29
  • 32
  • this isnt a bad answer, but the problem is that you are not taking advantage of jQuerys ability to "bubble up" events. Because you are binding events to each a tag individually you are creating 24 listeners, all with duplicate functionality. You can instead bind a listener to its closest common parent and only have one listener that listens for everything amonst its children. far more effient use of resources and easy to maintain. See my answer below for its use. – Kenneth Garza May 02 '13 at 00:11
0

you could bind an "on" event to the #christmasCalendar object

$("#christmasCalendar").on("click", "a", function(e){
    // handle link click event.
});

that will work for all the links

Kenneth Garza
  • 1,886
  • 14
  • 12