3

Here is my code:

function testimage() {
  var image;

  image = new Image();

  with (image) {
    id = "page1";
    border = 0;
    name = "IllustGIF";
    useMap = "#MAP1";
    src = "sample.gif" + "?d=" + new Date();

    // The event argument here is invalid; it's to show what is the desired result.
    onclick = function() { RecordMouseClick(event, this.id); };
  }

  // attached to body tag
  document.getElementById("body_ID").appendChild(image);
}

function RecordMouseClick(event, id) {
  alert("id: " + id + ", and event object should contain mouse x- and y- coordinates clicked");
}

I need to define the onclick event in JavaScript, not HTML. Now in HTML, it's easy -- just pass event as an argument to the function and, voila, event object in JavaScript But doing it all from scratch, all in JavaScript, without HTML, is challenging for me. When the reference function is called, it's supposed to record the element id and the mouse click x- and y- coordinates from the onclick event.

How can I pass an event to the onclick, such that the event object is valid at run-time?

Thank you.

3 Answers 3

5

Here's a sample fiddle.

image.onclick = function(e) { 
    e = e || window.event;
    RecordMouseClick(e, image.id); 
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your help. I appreciate the link and the solution.
Thanks. I've updated the fiddle to address firefox's clientX versus x for click event coordinates.
2
document.getElementById('id-of-the-html-element').onclick = function(){
// your code
};

or

function doSth(){
// your code
}

document.getElementById('id-of-the-html-element').onclick = doSth;

Read more about it over here: https://developer.mozilla.org/en/DOM/event

Comments

1

Try addEventListener().

image.addEventListener('click', 
    function(e) { 
        RecordMouseClick(e, this.id); 
    }, false);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.