0

I've wrote this simple code to attach events to one of my divs. But the events never seem to be fired. Here is my code:

$(function() {
    $(".ui-datepicker-prev").hover(function () {
      alert('H');
    });

    $(".ui-datepicker-prev").click(function () {
      alert('C');
    });

    $(".ui-datepicker-prev").mouseover(function () {
      alert('MO');
    });
});

P.S. I want to add event to next and prev buttons of jQuery DatePicker

2
  • Are you executing that at the end of your document or withing a doc.ready call? Commented May 10, 2012 at 16:47
  • yes i am executing that after my document gets ready. Commented May 10, 2012 at 16:57

2 Answers 2

7

Based on your updated question, I'm assuming that the elements you're selecting are created after DOM ready, in which case you'll most likely want to use event delegation. E.g.,

$(document).delegate('.ui-datepicker-prev', 'hover', function() {
    alert('H');
});

$(document).delegate('.ui-datepicker-prev', 'click', function() {
    alert('C');
});

$(document).delegate('.ui-datepicker-prev', 'mouseover', function() {
    alert('MO');
});

Please note that delegating hover and mouseover events is pretty expensive, so you may want to reconsider that. Another approach would be to bind directly to the elements (like you were attempting in your example), but wait to do so until after you know for sure the elements exist.

Sign up to request clarification or add additional context in comments.

2 Comments

I've updated the problem statement and the code. Please check it now. I've added more details of the problem. BTW my code was already wrapped in $(function(){ ... });
Both '.live' and '.delegate' work. I already selected another comment as correct answer. So I was only able to mark your comment as useful. Thanks for helping me out and sharing useful info.
0

If you are creating new elements try to use live()

$("#todayBtn").live("hover", function(){
  alert('H');
});

Also wrap your code in DOM ready

$(document).ready(function() {
  // Your code
});

2 Comments

I've updated the problem statement and the code. Please check it now. I've added more details of the problem. BTW my code was already wrapped in $(function(){ ... });
I tried live instead of .mouseover or .mouseout It worked. Because the buttons were created dynamically, I had to use live instead of simple event handlers. Thanks

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.