Proper way to structure In-line Component JavaScript to access DOM elements

  • 1
  • Question
  • Updated 3 years ago
  • Answered
Hi Community,

Here is the skeleton of my JavaScript:

var element = arguments[0],    
          $ = skuid.$;
element.append('<canvas id="myCanvas" width="800" height="50"></canvas>');
setInterval(function(){
    
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');    
    function ReachForTheStarsYaLongEaredGaloot(bunny) {
    }
    ReachForTheStarsYaLongEaredGaloot('Bugs');
    
}, 250);


Notice that I am using setIntervalI() to ensure that the DOM is loaded and I have access to the canvas element.  

This works but I am wondering what is the proper pattern?  

I suppose I could use this as an alternative:
$(document.body).one('pageload',function(){ ... });

Any guidance is appreciated.

Regards,
Irvin
Photo of Irvin Waldman

Irvin Waldman, Champion

  • 9,006 Points 5k badge 2x thumb

Posted 3 years ago

  • 1
Photo of Zach McElrath

Zach McElrath, Employee

  • 49,056 Points 20k badge 2x thumb
Irvin,

You shouldn't need to wait at all to access the DOM element --- to access a DOM element that you created with jQuery, just use element[0] or element.get(0) to get the raw, native DOM element:

var element = arguments[0],    
  $ = skuid.$,
  canvas = $('<canvas id="myCanvas" width="800" height="50">').appendTo(element),
  context = canvas[0].getContext('2d');

function ReachForTheStarsYaLongEaredGaloot(bunny) {
}

ReachForTheStarsYaLongEaredGaloot('Bugs');
    
Photo of Irvin Waldman

Irvin Waldman, Champion

  • 9,006 Points 5k badge 2x thumb
Awesome.  Thanks Zach.