admin管理员组

文章数量:1302869

Whenever I hover over the image it does not enlarge and gives an error.

HTML and Javascript code(these are two separate files):

var banner = document.getElementById("banner");

function enlargePic(){
banner.style.width = '800px';
banner.style.height  = '300px';
}

function normalPic(){
banner.style.width = '500px';
banner.style.height  = '200px';
}


banner.addEventListener("mouseover", enlargePic, false); 

banner.addEventListener("mouseout", normalPic, false); 

<div id="designs">
<a id="designs"></a>
<h1>DESIGNS.</h1> 
<table>
<tr>
<td><img src="banner2.jpg" id="banner"></td>
</tr>
</table>
</div>

Whenever I hover over the image it does not enlarge and gives an error.

HTML and Javascript code(these are two separate files):

var banner = document.getElementById("banner");

function enlargePic(){
banner.style.width = '800px';
banner.style.height  = '300px';
}

function normalPic(){
banner.style.width = '500px';
banner.style.height  = '200px';
}


banner.addEventListener("mouseover", enlargePic, false); 

banner.addEventListener("mouseout", normalPic, false); 

<div id="designs">
<a id="designs"></a>
<h1>DESIGNS.</h1> 
<table>
<tr>
<td><img src="banner2.jpg" id="banner"></td>
</tr>
</table>
</div>
Share Improve this question asked Apr 14, 2014 at 23:15 user3533879user3533879 11 gold badge1 silver badge2 bronze badges 3
  • 3 banner doesn't exist yet when you query it. Add the code after the markup, or in a document ready event. – elclanrs Commented Apr 14, 2014 at 23:20
  • What error? Elaborate. – Anubian Noob Commented Apr 14, 2014 at 23:33
  • What error is it giving you? Why do two elements have the same id in your HTML code? That is wrong! – Akinkunle Allen Commented Apr 14, 2014 at 23:46
Add a ment  | 

2 Answers 2

Reset to default 5

Your javascript code is in your first section. So it has rendered before banner element and cannot find the element id = banner because it has not rendered yet. Try to locate the code before the html code.

When referencing the function normalpic, you should preceed it with an empty function:

banner.addEventListener("mouseout",function(){normalpic},false)

本文标签: javascriptCannot read property 39addEventListener39 of null Errornot sure whyStack Overflow