1

The code is for a slider to switch images. When I run the page I get this error:

Cannot set property 'onclick' of null.

HTML:

   <!DOCTYPE html>
   <html lang="en">
   <head>
<meta charset="UTF-8">
<title>Image Slider</title>
<link rel="stylesheet" type="text/css" href="sliderswag.css">
<script language="javascript" type="text/javascript" src="imgslidescript.js"></script>
</head>
<body>
<div id="box">
    <img id="main" src="http://lmetar.com/oscar1.jpg">
    <img id="left" src="http://lmetar.com/left.png">
    <img id="right" src="http://lmetar.com/right.png">
</div>

JavaScript:

 document.getElementById('left').onclick = slideChange;
document.getElementById('right').onclick = slideChange;
var slideNumber = 0;
function slideChange()
{
    slideNumber += 1;
    if (slideNumber > 3)
    {
        slideNumber = 1;
    }
    else
    {
        document.getElementById('main').src = 'http://lmetar.com/oscar' + slideNumber + '.jpg';
    }
}
Sam Hanley
  • 4,707
  • 7
  • 35
  • 63
dmaster
  • 41
  • 5
  • That probably means that your JS is being executed before the DOM loads. Either wrap the code in a DOM loaded callback, or move the position of the ` – Josh Crozier Dec 01 '15 at 20:40
  • place your `script` tag at the bottom – Ramanlfc Dec 01 '15 at 20:40
  • Possible duplicate of [Where is the best place to put – Kenney Dec 01 '15 at 20:45

2 Answers2

6

Move your script to the end of your page. You're running JavaScript on elements that don't yet exist.

Or wrap the code you have in a window.onload call which will execute the code after the window has loaded. Ex:

 window.onload = function () {
   document.getElementById('left').onclick = slideChange;
   document.getElementById('right').onclick = slideChange;
   var slideNumber = 0;

   function slideChange() {
     slideNumber += 1;
     if (slideNumber > 3) {
       slideNumber = 1;
     } else {
       document.getElementById('main').src = 'http://lmetar.com/oscar' + slideNumber + '.jpg';
     }
   }
 };
j08691
  • 204,283
  • 31
  • 260
  • 272
  • Consider adding an event listener attached to the document instead of a `window.onload`. See Druzion's answer. – Nick Zuber Dec 01 '15 at 20:48
0

Your JavaScript is loading before you content, therefore it is trying to find elements that do not exists. You have 2 options:

  1. Move your <script> tag to the end of your page
  2. Use the following to wait until the page has loaded before you execute your script

Code:

document.addEventListener("DOMContentLoaded", function(event) { 
  // Your Code Here
});
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54