Mohandass
Mohandass

Reputation: 157

jQuery has no reference

I have a link. I need to write a click function for the element on click. so i have written a code like this.

<div class="tabCon">
  <ul>
    <li><a href="javascript:void(0);" id="Overview">Overview</a></li>
    <li><a href="javascript:void(0);" id="ProjDet">Project Details</a></li>
    <li><a href="javascript:void(0);" id="Directions">Directions</a></li>                                         
  </ul>
<div>

I have written a js file in which i have written so many functions.

$('.tabCon > ul > li > a').click(function() { 
   alert('Link Clicked !');
});

But this wont works when i declare the reference for this JavaScript file in the head section.

This works when i declare below the element or before the closing of body tag

why this happens ? is any other ways ?

Upvotes: 0

Views: 105

Answers (5)

pad31
pad31

Reputation: 58

Do u have put this function $("...").click(...); in a $(function(){ ... } block so it's active when the page is loaded. If not, this is normal that this won't work.. Try to put your function in a $(function(){ ... } block and it will works.

Pad.

Upvotes: 0

Theofanis Pantelides
Theofanis Pantelides

Reputation: 4854

Because if you add it in the head, the element hasn't been created in the DOM yet, so you cannot access it as an object via JavaScript!

$(document).ready(function () {
  $('.tabCon > ul > li > a').click(function() { 
   alert('Link Clicked !');
  });
});

Try the above!

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039170

Make sure that you are executing your jQuery code inside a document.ready handler if you put it in the head section otherwise the DOM might not yet be loaded and ready to be manipulated when you try to attach a click handler to some element:

$(function() {
    $('.tabCon > ul > li > a').click(function() { 
       alert('Link Clicked !');
    });
});

Upvotes: 1

Morgan Harris
Morgan Harris

Reputation: 2619

Make sure you've got the jQuery call inside your document.ready event.

Basically, if you're writing jQuery in the HEAD block, wrap the whole thing in

$(function() {

//jquery code goes here

});

Upvotes: 0

colinross
colinross

Reputation: 2085

The element doesn't exist in the DOM when the parser is in the head, but by the time it (the javascript parser) reaches the closing body tag, it does. That is why.

Upvotes: 0

Related Questions