views:

110

answers:

2

I have a simple single page setup. Under a root folder, I have 3 subfolders (js, css, and images). In the root folder, I have an index.html page with the following content:

<html>
<head>
<title></title>
<script language="javascript" src="js/jquery-1.3.2.min.js"></script>
<script language="javascript" src="js/myscript.js"></script>
</head>
<body>
<a onclick="doSomething()" href="#" class="doSomething">Click!</a>
</body>
<html>

myscript.js contains the following code:

$('a.doSomething').click(function(){
//Do Something here!
alert('You did sometihng, woo hoo!');
});

When I click the link, nothing happens. What am I missing?

+10  A: 

Wrap document.ready around the code:

$(document).ready(function() {
    $('a.doSomething').click(function(){
        //Do Something here!
        alert('You did sometihng, woo hoo!');
        return false; // return false to prevent default action
    });
});

As it is right now, you are trying to bind an event to an element that does not yet exist in the DOM.

Also, not sure why you have the onclick on the link itself, as the whole point of jQuery is to be able to take those ugly inline events out of there and bind them cleanly in the javascript. If you do this:

<a href="#" class="doSomething">yay click me</a>

And then use the code above, it should work fine.

Paolo Bergantino
wouldn't that be "wrap document.ready around the code" ?
Javier
Thanks Paul. I am following a tutorial on how to use jquery properly. It talks about using unobtrusive javascript. I am not sure how to do it with the onclick though. Here is the link if you are interested:http://www.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/
Xaisoft
lol, you answered my question before I posted it. Thanks agin.
Xaisoft
Just realized I mispelled your name. Sorry about that Paolo.
Xaisoft
No problem. :) Good luck with it, jQuery is awesome once you get the hang of it.
Paolo Bergantino
A: 

At first I thought you were just missing a function named "doSomething". Then I realized you where expecting your selector to find the anchor tag anyway. However, that won't happen. At the time your script runs, the anchor hasn't been added to the DOM yet.

Joel Coehoorn