I have a simple link:
<a href="#" id="test">Test Link</a>
I want to get an alert whenever this link is pressed, so I add:
<script>
$('#test').click(function() { alert('clicked!'); } );
</script>
and it works fine, but when i move this code to a remote javascript file, it doesn’t work..
any idea why?
I’ve also tried this code:
$(document).ready(function() {
$('#test').click(function() { alert('clicked!'); });
});
Your second example, using the
readyfunction, should be working. Your first example should also work provided you include the script below the element with the ID “test” (the element has to already exist when your script runs, since you’re not waiting for DOM ready). In both cases, your script must be included below (after) the jQuery script.Example when you don’t use
readyExample when you do use
readyI’d check that your external file is actually getting loaded (look for 404 errors in the browser console).
Update: From your comment below, the problem is that the “test” element doesn’t exist when you’re trying to hook up the handler.
clickonly sets up the handler on the element if it already exists. If you’re creating the element later, you have three options (two of which are really the same):successcallback of the ajax call you’re making).live, which basically hooks theclickevent document-wide and then checks to see if the element you tell it (“#test”, in this case) was clicked.delegateon the appropriate container (the element within which you’re adding “test”).delegateis a more targeted version oflive.liveanddelegateare both examples of a technique called event delegation, which jQuery makes easy for you by providing those methods.See the links for further information and examples, but for example, suppose you’re going to be adding the “test” element to an element with the ID “target”. You’d use
delegatelike this:That hooks the
clickevent on “target”, but acts a lot like you’ve just magically hooked it on “test” as soon as “test” was added. Within your handler,thisrefers to the “test” element just as withclick.