views:

45

answers:

2

Can someone please help with converting this code to plain JS:

$(document).ready(function() {
    $("textarea").bind("keydown", function(event) {
        var textarea = $(this).get(0);          
        //further will need only textarea and event vars
    }
});

I don't care about cross browser compatibility as long as it works in current FF and Chrome.

A: 

Why convert it to "plain JS"? jQuery essentially is plain JS. It's just a language built around Javascript. What is it that's not working for you with jQuery

Zane Edward Dockery
Probably to remove the need to load the jQuery library.
Gert G
+5  A: 

Your selector is quite simple, you are looking for all the textarea elements, then you can use the document.getElementsByTagName method.

To simulate $(document).ready, we can bind the DOMContentLoaded event e.g.:

document.addEventListener('DOMContentLoaded', function () {
  var allTextAreas = document.getElementsByTagName('textarea');
  // event handler
  var handler = function (event) {
    var textarea = this;
    //...
  };

  // iterate over the textareas and bind the event
  for(var i = 0, len = allTextAreas.length; i < len; i++) {
    allTextAreas[i].addEventListener('keydown', handler, false);
  } 
}, false);

For CSS selectors, you can use the querySelectorAll method, available on both browsers you are targeting.

See also:

CMS
i would also add `window.onDomReady(onReady)` for `$(document).ready`
Sinan Y.
This works, thanks. The only problem is I can't seem to find a way to stop event propagation. I used to just return false from event handler and it would stop all further event processing. Any idea how to make it work in plain js? Thanks again.
serg
@serg555: Yes, the `addEventListener` method doesn't really expect any return value from the handler, you can use the [`event.stopPropagation()`](https://developer.mozilla.org/en/DOM/event.stopPropagation) method, to stop the normal event flow. Note that in jQuery, returning `false` from an event handler, stops the event propagation and prevents the default action, [more info](http://stackoverflow.com/questions/2017755/).
CMS