ftkzdg
Last Updated: February 25, 2016
·
692
· mlb

Initialize functions before DOM ready but with the right Elements

Lets admit that I want my functions to be evaluated before "DOM ready".
Here, doSomething will represent this.
Declaring a myElement variable in the top scope lets me initialize my functions with the right myElement which is defined when the DOM is ready, caching the right Element.
This can be useful if you want to organize your code with almost only DOM queries inside Element.ready.

;(function(){
  var myElement

  function doSomething(){
    var data = myElement.serialize() // …
  }

  Object.extend(myNamespace, {
    doSomething : doSomething
  })

  Element.ready(function(){

    myElement = $("any-id")

  })

})()

NOTE : Element.ready is a Craft.js function, adapt this with your usual domReady choice.