Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError is Null?

This is an error in Firebug I keep seeing.

TypeError: $("#gallery-nav-button") is null
 [Break On This Error]  
$('#gallery-nav-button').addClass('animated fadeOutRightBig');

Here is my code:

JS

$(function() {
  $("#close-gallery-nav-button").click(function() {
    $('#gallery-nav-button').addClass('animated fadeOutRightBig');
   });
});

HTML

<div id="gallery-nav-button">
  <h4 id="close-gallery-nav-button">X</h4>
    <h3 class="text-center small-text"><a class="inline text-center small-text" href="#gallery-nav-instruct">Click Here for Gallery <br /> Navigation Instructions.</a></h3>
</div>

CSS

#close-gallery-nav-button{
  text-indent:-9999px; 
  width:20px; 
  height:20px; 
  position:absolute; 
  top:-20px; 
  background:url(/images/controls.png) no-repeat 0 0;
}
#close-gallery-nav-button{background-position:-50px 0px; right:0;}
#close-gallery-nav-button:hover{background-position:-50px -25px;}
like image 391
L84 Avatar asked Sep 26 '12 23:09

L84


2 Answers

I also want to add - because this is the #1 Google search result for the important error message "TypeError: [x] is null" - that the most common reason a JavaScript developer will get this is that they are trying to assign an event handler to a DOM element, but the DOM element hasn't been created yet.

Code is basically run from top to bottom. Most devs put their JavaScript in the head of their HTML file. The browser has received the HTML, CSS and JavaScript from the server; is "executing"/rendering the Web page; and is executing the JavaScript, but it hasn't gotten further down the HTML file to "execute"/render the HTML.

To handle this, you need to introduce a delay before your JavaScript is executed, like putting it inside a function that isn't called until the browser has "executed" all of the HTML and fires the event "DOM ready."

With raw JavaScript, use window.onload:

window.onload=function() {
   /*your code here*
   /*var date = document.getElementById("date");
   /*alert(date);
}

With jQuery, use document ready:

$(document).ready(function() {
   /*your code here*
   /*var date = document.getElementById("date");
   /*alert(date);
});

This way, your JavaScript won't run until the browser has built the DOM, the HTML element exists (not null :-) ) and your JavaScript can find it and attach an event handler to it.

like image 97
Andrew Koper Avatar answered Sep 21 '22 13:09

Andrew Koper


I have several scripts running on this page and evidently one script was conflicting with another. To solve my issue I added jQuery.noConflict();

var $j = jQuery.noConflict();
$j(function() {
  $j("#close-gallery-nav-button").click(function() {
    $j('#gallery-nav-button').addClass('animated fadeOutRightBig');
   });
});
like image 13
L84 Avatar answered Sep 23 '22 13:09

L84