Loading ...
Sorry, an error occurred while loading the content.

Re: [ydn-javascript] New to YUI and Javascript and have some questions

Expand Messages
  • Eric Miraglia
    Joey, The reason why you re getting null from your first test is that your submit element is not present on the page when that code executes (it executes
    Message 1 of 3 , Dec 31, 2008
    • 0 Attachment
      Joey,

      The reason why you're getting null from your first test is that your submit element is not present on the page when that code executes (it executes immediately).  Try:

      (function init()
      {
      YAHOO.util.Event.onDOMReady(function() {
      var testvar=document.getElementById("submit");
          
      console.log(testvar);
      });
      })();

      The wrapping init function is probably unneccessary in this case.

      The reason why the Core.start version works is that the Core.start method automatically attaches to the window load event, so even though you call start before submit is present on the page, by the time it looks for that element the page is fully loaded.

      Regards,
      Eric


      On Dec 30, 2008, at 11:25 PM, Joey wrote:

      I am new to YUI, and basically new to JavaScript. To start learning YUI I decided I was going to play with event listeners just to get the hang of it. I ran into a problem I didn't expect. When I used getElementByID and go to view the result in firebug it comes out null. However if I use the Core Library from the Simply JavaScript book that I started learning JavaScript with it actually gives me the element in firebug. How do I use YUI to get the element? I have attached my code below

      test3.js
      (function init()
      {
          var testvar=document. getElementById( "submit") ;
          console.log( testvar);
      })();
      var CoreTest=
      {
          testvar:null,
          init:function( )
          {
              var testvar=document. getElementById( "submit") ;
               console.log( testvar);
          }
      };
      Core.start(CoreTest );


      test.php
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www. w3.org/TR/ xhtml11/DTD/ xhtml11.dtd">
      <html xmlns="http: //www.w3. org/1999/ xhtml">
      <head>
      <meta http-equiv=" Content-Type" content="text/ html; charset=utf- 8" />
      <title>Untitled Document</title>
      <!--<script type="text/javascri pt" src="http:// yui.yahooapis. com/combo? 2.6.0/build/ yahoo-dom- event/yahoo- dom-event. js&2.6.0/build/ connection/ connection- min.js&2.6.0/build/ dragdrop/ dragdrop- min.js&2.6.0/build/ element/element- beta-min. js&2.6.0/build/ json/json- min.js&2.6.0/build/ selector/ selector- beta-min. js"></script>-->
      <script type="text /javascri pt" src="functions/ js/core.js"></script>
      <!--<script type="text/javascri pt" src="functions/ js/dom-min. js"></script>
      <script type="text/javascri pt" src="functions/ js/event- min.js"></script>
      <script type="text/javascri pt" src="functions/ js/element- beta-min. js"></script>-->
      <!--<script type="text/javascri pt" src="functions/ js/yahoo- dom-event. js"></script>-->
      <!--<script type="text/javascri pt" src="http:// yui.yahooapis. com/2.6.0/ build/yahoo/ yahoo-min. js" ></script>-->
      <script type="text/javascri pt" src="http:// yui.yahooapis. com/combo? 2.6.0/build/ yahoo-dom- event/yahoo- dom-event. js"></script>
      <script type="text/javascri pt" src="test3.js"></script>
      </head>

      <body>
      < ;form enctype="applicatio n/x-www-form- urlencoded" method="post" action="" id="form">
          <div>
              <input name="k" type="text" disabled="disabled" />
              <input name="submit" type="button" id="submit" />
          </div>
      </form>
      <div id="testdiv">
          Hello
      </div>
      </body>
      </html>

      Core.js - Core Library from Simply Javascript
      //  core.js
      //  ------------ --------- --------- --------- --------- --------- --------- ---
      /*  From the code archive for Simply JavaScript by Yank and Adams, 2007.
       *  Edited by ccv to eliminate JSlint errors.
       */

      var Core = {};

      // W3C DOM 2 Events model
      if (document.addEventL istener)
      {
        Core.addEventLi sten er = function(target, type, listener)
        {
          target.addEventList ener(type, listener, false);
        };

        Core.removeEventLis tener = function(target, type, listener)
        {
          target.removeEventL istener(type, listener, false);
        };

        Core.preventDefault = function(event)
        {
          event.preventDefaul t();
        };

        Core.stopPropagatio n = function(event)
        {
          event.stopPropagati on();
        };
      }
      // Internet Explorer Events model
      else if (document.attachEve nt)
      {
        Core.addEventListen er = function(target, type, listener)
        {
          // prevent adding the same listener twice, since DOM 2 Events ignores
          // duplicates like this
          if (Core._findListener (target, type, listener) != -1) { return ; }

          // listener2 calls listener as a method of target in one of two ways,
          // depending on what this version of IE supports, and passes it the global
          // event object as an argument
          var listener2 = function()
          {
            var event = window.event;

            if (Function.prototype .call)
            {
              listener.call( target, event);
            }
            else
            {
              target._currentList ener = listener;
              target._currentList ener(event) ;
              target._currentList ener = null;
            }
       &nb sp;  };

          // add listener2 using IE's attachEvent method
          target.attachEvent( "on" + type, listener2);

          // create an object describing this listener so we can clean it up later
          var listenerRecord =
          {
            target: target,
            type: type,
            listener: listener,
            listener2: listener2
          };

          // get a reference to the window object containing target
          var targetDocument = target.document || target;
          var targetWindow = targetDocument. parentWindow;

          // create a unique ID for this listener
          var listenerId = "l" + Core._listenerCount er++;

          // store a record of this listener i n the window object
          if (!targetWindow. _allListeners) { targetWindow. _allListeners = {}; }
          targetWindow. _allListeners[ listenerId] = listenerRecord;

          // store this listener's ID in target
          if (!target._listeners ) { target._listeners = []; }
          target._listeners[ target._listener s.length] = listenerId;

          // set up Core._removeAllList eners to clean up all listeners on unload
          if (!targetWindow. _unloadListenerA dded)
          {
            targetWindow. _unloadListenerA dded = true;
            targetWindow. attachEvent( "onunload" , Core._removeAllList eners);
          }
        };

        Core.removeEventLis tener = function(target, type, listener)
        {
           // find out if the listener was actually added to target
          var listenerIndex = Core._findListener( target, type, listener);
          if (listenerIndex == -1) { return; }

          // get a reference to the window object containing target
          var targetDocument = target.document || target;
          var targetWindow = targetDocument. parentWindow;

          // obtain the record of the listener from the window object
          var listenerId = target._listeners[ listenerIndex] ;
          var listenerRecord = targetWindow. _allListeners[ listenerId] ;

          // remove the listener, and remove its ID from target
          target.detachEvent( "on" + type, listenerRecord. listener2) ;
          target._listeners. splice(listenerI ndex, 1);

          / / remove the record of the listener from the window object
          delete targetWindow. _allListeners[ listenerId] ;
        };

        Core.preventDefault = function(event)
        {
          event.returnValue = false;
        };

        Core.stopPropagatio n = function(event)
        {
          event.cancelBubble = true;
        };

        Core._findListener = function(target, type, listener)
        {
          // get the array of listener IDs added to target
          var listeners = target._listeners;
          if (!listeners) { return -1; }

          // get a reference to the window object containing target
          var targetDocument = target.document || target;
          var targetWindow = targetDocument. parentWindow;

          // searching backward (to speed up onunload processing), fi nd the listener
          for (var i = listeners.length - 1; i >= 0; i--)
          {
            // get the listener's ID from target
            var listenerId = listeners[i] ;

            // get the record of the listener from the window object
            var listenerRecord = targetWindow. _allListeners[ listenerId] ;

            // compare type and listener with the retrieved record
            if (listenerRecord. type == type && listenerRecord. listener == listener)
            {
              return i;
            }
          }
          return -1;
        };

        Core._removeAllList eners = function()
        {
          var targetWindow = this; 

          for (var id in targetWindow. _allListeners)
          {
            var listenerRecord = targetWindow. _allListeners[ id];
            listenerRecord. target.detachEve nt(
                "on" + listenerRecord. type, listenerRecord. listener2) ;
            delete targetWindow. _allListeners[ id];
          }
        };

        Core._listenerCount er = 0;
      }

      Core.addClass = function(target, theClass)
      {
        if (!Core.hasClass( target, theClass))
        {
          if (target.className === "")
          {
            target.className = theClass;
          }
          else
          {
            target.className += " " + theClass;
       &nb sp;  }
        }
      };

      Core.getElementsByC lass = function(theClass)
      {
        var elementArray = [];

        if (document.all)
        {
          elementArray = document.all;
        }
        else
        {
          elementArray = document.getElement sByTagName( "*");
        }

        var matchedArray = [];
        var pattern = new RegExp("(^| )" + theClass + "( |$)");

        for (var i = 0; i < elementArray. length; i++)
        {
          if (pattern.test( elementArray[ i].className) )
          {
            matchedArray[ matchedArray. length] = elementArray[ i];
          }
        }

        return matchedArray;
      };

      Core.hasClass = function(target, theClass)
      {
        var pattern = new RegExp("(^| )" + theClass + "( |$)");

        if (pattern.test( target .className ))
        {
          return true;
        }

        return false;
      };

      Core.removeClass = function(target, theClass)
      {
        var pattern = new RegExp("(^| )" + theClass + "( |$)");

        target.className = target.className. replace(pattern, "$1");
        target.className = target.className. replace(/ $/, "");
      };

      Core.getComputedSty le = function(element, styleProperty)
      {
        var computedStyle = null;

        if (typeof element.currentStyl e != "undefined")
        {
          computedStyle = element.currentStyl e;
        }
        else
        {
          computedStyle = document.defaultVie w.getComputedSty le(element, null);
        }

        return computedStyle[ styleProperty] ;
      };

      Core.start = function(runnable)
      {
        Core.addEventListen er(window, "load", runnable.init) ;
      };


    Your message has been successfully submitted and would be delivered to recipients shortly.