Search code examples
ajaxprototypejsobserver-pattern

prototype: keydown on document, stop observing when in form


I am trying to make next/previous page with ajax left/right arrows keys working (like on facebook). Everything is fine and works, but I also have form on my page and if user focus on that form I want to stop observing left/right key, because without that you can't move with arrows in the form, you are getting next/previous image instead of movement in the form.

My actual code is here, the comment_name is id of the field, if I first click into the field then the observing of the keydown is stopped. But if I first press left/right key then clicking into form does not stop observing.

It seems to me like it can't work with ajax-returned html...?

document.observe("dom:loaded", function() {

  document.observe('keydown', function(event){
    if(event.keyCode == Event.KEY_RIGHT) {
      if (Prototype.Browser.IE) {
        $('next').click();;
      }
      else {
        $('next').simulate('click');
      }
    }
  });

  $('comment_name').observe('focus', function(event){
   document.stopObserving('keydown');
  });

The page is here http://beta.sigut.net/photos/2027, the current code in javascripts/application.js

Thank you very much! maybe my approach is all wrong...


Solution

  • You have to bind the observe every time new AJAX content is loaded. That means calling

      $('comment_name').observe('focus', function(event){
       document.stopObserving('keydown');
      });
    

    After adding the AJAX loaded html into the DOM.