1

How can I pass an object to a function in innerHTML?

Here is an example:

function clickme()
{
  var coord = {x:5, y:10};
  testimageih(coord);
}

function testimageih(coord)
{
  var html = "<img id=\"sam1\" border=\"0\" name=\"sam1\" src=\"sample.gif\" " +
             "onLoad=\"ImageOnLoad(" + coord + ");\"></img>";
  document.getElementById("content").innerHTML = html;

}

function ImageOnLoad(coord)
{
  if (coord) alert("Success"); 
  else alert("Fail");
}

How can I pass this object, coord? It's my only other recourse, at the moment, is passing coord.x and coord.y, instead of the object.

Thank you.

3 Answers 3

4

The simplest way is to create an image, attach the event handler and insert the element using DOM methods.

function testimageih(coord)
{
  var img = document.createElement('img');
  img.id = 'sam1';
  img.border = 0;
  img.name = 'sam1';
  img.src = 'sample.gif';
  img.onload = function() {
    ImageOnLoad(coord);
  };

  document.getElementById('content').appendChild(img);    
}

Note that this has one difference to the code you have above: it doesn't remove any elements currently in #content. If that will happen, you will have to do the removal separately.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use document.createElement instead of innerHTML.

// Create the element
var element = document.createElement('img');
element.setAttribute('border', 0);
element.setAttribute('name', 'sam1');
element.setAttribute('src', 'sample.gif');

// Attach onLoad handler to it (passing it the object)
element.onload = function() { ImageOnLoad(coord) };

// Replace the contents of your... div?
var content = document.getElementById("content")
content.innerHTML = '';
content.appendChild(element);

Comments

1

The way you are implementing it now, yes--you're creating HTML as a string, and embedding JavaScript within that string; your options are limited.

And geez, use single-quotes around the html var so you don't have to escape everything :(

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.