Use onmousedown to get the ID of the element you just mousedowned on?

Chris Sobolewski picture Chris Sobolewski · Aug 9, 2009 · Viewed 16.7k times · Source

Is this possible?

I am attempting to write a function for onmousedown that will return the ID of the element you just clicked for later use in recreating that element in a different div.

Answer

Christian C. Salvadó picture Christian C. Salvadó · Aug 9, 2009

You can use event delegation, to basically connect only one event handler to your entire document, and get the element which the event was originally dispatched, using event.target:

document.body.onmousedown = function (e) {
  e = e || window.event;
  var elementId = (e.target || e.srcElement).id;

  // call your re-create function
  recreate(elementId);
  // ...
}

function recreate (id) {
  // you can do the DOM manipulation here.
}

Edit: You can assign events to all your Scriptaculous draggables in this way:

Event.observe(window, 'load', function () {
  Draggables.drags.each(function (item) {
    Event.observe(item.element, 'mousedown', function () {
      alert('mouseDown ' + this.id); // the this variable is the element 
    });                              // which has been "mouse downed"
  });
});

Check an example here.