I am trying to solve a problem for a client where they want to dynamically inject an image into the page and have it call their js function when clicked. The script is included from our base js class to their site, so it's my code on their site essentially.
I am very close to getting there, but I've found a strange issue in IE of all places, lol.
Using jQuery,
$('#sas-window-header').append("<img src='sandwich.jpg' id='gif' alt='Sandwich' />");
This is throwing an error in IE7,8
Object expected attachevent, line 42 character 20
(attachevent is the name of my page)
I was trying to write my function using vanilla js, but it seems that there are too many issues between attachEvent()
and addEventListener()
to make it viable, hence injecting jQuery to help me out.
Can anyone tell me why IE thinks that a cross browser frameworks function methods should be expecting an object?
I am getting expected behaviour in Firefox, Safari and Chrome. Two images in Opera for some reason, and IE7,8 with this object error. I'll come to ie6 later! ;)
Here is what I have so far,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Attach event test page</title>
<script type="text/javascript">
window.onload = (function() {
if(typeof jQuery == 'undefined'){
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js";
script.type = "text/javascript";
script.onload = script.onreadystatechange = function(){
injectImg();
};
document.body.appendChild( script );
}else{
injectImg();
}
});
function injectImg(){
$('#sas-window-header').append("<img src='sandwich.jpg' id='gif' alt='Sandwich' />");
$('#gif').click(function(){
alert('Clicked');
})
}
</script>
</head>
<body>
<p>The header</p>
<div id="sas-window-header"></div>
</body>
</html>