Question

In the program I'm writing I need to be able to access the node that is sending an event in javascript.

I have been unsuccessful in using this, as it is referring to the object in my code. So the following doesn't work.

var node = new node();

// Node Object
function node() {

// Create Sibling Node
this.createSibling = function() {
 var node = createNode();
 this.parentNode.appendChild(node); } }

When I call the function createNode() it assembles a link that has an event onclcick attached to it called node.createSibling() and node.createChild() on a different link.

I'm currently using var NODETREE as the parent because I'm don't know how to get the node that is begin clicked. This is keeping me from being able to create node with their own children and siblings; only the main node can get them.

    var node = new node();

   // Node Object
   function node() {

   // Instance Veriables    
   var NODETREE = document.getElementById('node-tree');

   // Create Sibling Node
   this.createSibling = function() {
   var node = createNode();
   NODETREE.appendChild(node); } }

How do I access the node that has the onclcick event attached that is being clicked, without having to create a load of code, so I can create children and siblings for the nodes that I have created and not just the trunk?

NOTE:

I need to do this without jQuery or another framework.

Was it helpful?

Solution

When an element has an eventhandler the Event object is passed to the event handler. This event object has amongst other things a reference to the node that triggered the event.

So...

var createSibling = function(_event){
  var e = this; // the element this function is actually attached to
  var event_e = _event.target; //another way to get at the element clicked

  // do stuff
};

document.getElementById('myElement').onClick = createSibling;
document.getElementById('myElement').captureEvents(Event.CLICK);

The problem is the property names for different things differ cross browser - this is another reson to use a framework because they will implement the browser detection ans specific implementations which you will need to do if you do not use one.

See quirksmode.org for some advanced details: http://www.quirksmode.org/js/introevents.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top