0

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
}

2 Answers 2

1

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) });
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

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.