My JQuery doesn't affect the page

I use jade and node.js and express

I have the following index.jade page (with no layout.jade page):

script(type='text/javascript', src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js') script(type='text/javascript', src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js') script(type='text/javascript', src='/javascripts/underscore-min.js') script(type='text/javascript', src='/javascripts/backbone-min.js')
script(type:'text/javascript')

script $(function() { $('a').on('click', function() { alert("You clicked me!"); }); });

a(href="") link1 br a(href="") link2 br a(href="") link3

I expected to be alerted with "You clicked me!" whenever I click the link but from some reason nothing happened.

Can someone identify what I am doing wrong?

.... The case is closed but I found what is wrong with the code: The problem with this code is that the object $('a') has no has no method 'on'

Thanks in advance, Shai

Short Answer

$(function() {
  $('a').on('click', function() {`
    alert("You clicked me!");
  });
});

Long Answer

It's a bit hard to tell from your code since it's not formatted it properly (easiest way is to copy/paste it into an editor that lets you tab entire blocks like Sublime Text2, Notepad++, etc) but I think the issue is the order of the event binding.

<script> tags in HTML are executed as soon as they appear in the DOM. That means that you cannot refer to tags in the DOM that haven't existed yet. If your case (again hard to tell from the code so guessing here) the <a href ...> anchor tag appears after the event binding for the click handler.

Two solutions are either:

  1. Move the event binding after the anchor tag is declared
  2. Put the event binding in block that isn't executed till the DOM is read. This is the preferred approach as it decouples the order of loading various pieces of your page. With jQuery this is accomplished by passing an anonymous function to $. Put the code above in a script block anywhere on the page (after the jQuery include).