Reputation: 15
I have this code but the img.onclick
isn't functioning and couldn't figure out what's the reason. Could someone give me some advice? Thanks
var img = document.createElement('img');
img.src = "images/tv.jpg";
img.width = "280";
img.height = "200";
img.onclick = function () {
window.location.href = "~/HEMS/EditDevice.cshtml";
}
...............
cell.appendChild(img);`
Upvotes: 0
Views: 298
Reputation: 10191
Try
var img = document.createElement('img');
img.src = "images/tv.jpg";
img.width = "280";
img.height = "200";
img.onClick = function () {
window.location.href = "~/HEMS/EditDevice.cshtml";
}
...............
cell.appendChild(img);
I believe it's onClick not onclick.
In addition the url you're redirecting to appears to be an MVC page using tilda notation, as this is a server side concept this is not going to work in JavaScript.
Upvotes: 0
Reputation: 65
try this one:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="content">
content
</div>
<script type="application/javascript">
var img = document.createElement('img');
img.src = "grid.png";
img.width = "280";
img.height = "200";
img.onclick = function () {
window.location.href = "~/HEMS/EditDevice.cshtml";
}
var cnt = document.getElementById('content');
cnt.appendChild(img);
</script>
</body>
</html>
Upvotes: 0
Reputation: 28528
It is working perfectly, You need to make sure that url is correct for changing page location:
var img = document.createElement('img');
img.src = "images/tv.jpg";
img.width = "280";
img.alt='Url not exist';
img.height = "200";
img.onclick = function () {
alert('1');
}
document.getElementById("cell").appendChild(img);
Upvotes: 1