Reputation: 45
I am trying to make a "for" loop that adds a function to each day in a calendar which on click builds a card with lesson descriptions of the current day that was clicked.
My problem is that it builds all the cards of all days in the month the second I load the calendar without waiting for me to click on specific element.
This is part of my code that is relevant for this problem:
for(let i=1;i<=numberOfDays;i++){ //go through all days and building them in a calendar
$(`ul.days`).append(`
<li class="day${i}">${i}</li>
`)
lessons(date,i); //this just mark the days that have lessons in them
$(`day${i}`).click(showCard(date,i)); //for each day adds a function
}
Upvotes: 0
Views: 41
Reputation: 68933
You can use on()
to attach event for dynamically created elements. Then call the function inside of an anonymous function like the following:
Change:
$(`day${i}`).click(showCard(date,i));
To
$('ul').on('click', `.day${i}`, function { showCard(date,i) });
Upvotes: 1
Reputation: 61
You have to bind the element with the event
for(let i=1;i<=numberOfDays;i++){ //go through all days and building them in a calendar
$(`ul.days`).append(`
<li class="day${i}">${i}</li>
`)
lessons(date,i); //this jsut mark the days taht have lessons in them
$(`day${i}`).bind( "click", function() {showCard(date,i)}); <--//for each day adds a function
}
Upvotes: 0