Reputation: 9547
I have a div with an id called #wrapper
. Next to it I have button. When the button is clicked, an ajax call is triggered returning a list of divs with a class called .calendarDate
. Everything works great, #wrapper
is populated fine.
Now I am trying to have a click event on that .calendarDate
class, but it is not working. The strange part is that the CSS properties I apply to that class are working properly. Hope someone can acknowledge about that strange behavior. By he way, no errors in my debugger. Thank you in advance for your replies. Cheers. Marc
My PHP: working great
Here i set my variables...
while($input<$inDays){
++$input;
$test=$input." days";
if($input<0){$attribut='"avant"';}else{$attribut='"apres"';}
echo '<div class="calendarDate" indiDate=' .$attribut. '>' .date('Y-m-d', strtotime($test)). '</div>';
}
My JS:
$(document).ready(function() {
$('#wrapper').load('php/calendar2.php');
$('.calendarDate').click(function(){
alert('Whaou!');
});
});
My HTML:
<div id="wrapper"></div>
<input id="envoyer" type="submit" multiplicateur="1">
Upvotes: 0
Views: 113
Reputation: 11454
The element doesnt exist when you bind the event in document ready? You need to bind the click event onto .calendardate
after the ajax call is successful and you've injected the markup into the dom - or use .live
or .delegate
instead of .click
.
Upvotes: 1
Reputation: 193291
You bind your click event with click
. Instead use delegate
or on
. If you are using jQuery < 1.7 you should use .delegate()
:
$('#wrapper').delegate('.calendarDate', 'click', function() {
// this should work
});
If you are using jQuery 1.7+ you should use .on()
:
$('#wrapper').on('click', '.calendarDate', function() {
// this should work
});
Upvotes: 2
Reputation: 230
$('.calendarDate').bind('click', function() {
alert('Replace the alert with your code.');
});
That's really all I can say without seeing your code to check for errors. If you have elements that are generated dynamically try replacing the .bind() with .live().
Upvotes: 0
Reputation: 26143
It sounds like you're binding the click event to the calendarDate class before it exists. Try using this to bind the event handler instead...
$(document).on("click", ".calendarDate", function() {
// etc
}
That will fire the click event handler to all elements with a class of calendarDate, regardless of whether they exist at document ready or not.
Upvotes: 4
Reputation: 7489
A likely cause of the issue (can't be sure without seeing the code) is that you are trying to bind the click events when the page loads, so the .calendarDate
elements do not exist. Make sure you don't add the click events for the .calendarDate
elements until after you add the .calendarDate
elements to the page.
Upvotes: 1