I have a really strange problem. My example code works [here][1] quite fine, but I have the exactly same code in my aptana studio editor and when I try it in Chrome or the Eclipse browser the events just don’t fire. I can’t imagine what’s the problem, because it’s exactly the same code …
HTML
<!DOCTYPE html>
<html>
<head>
<title>OrderScreen</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/script.js" type="text/javascript"></script>
</head>
<body>
<a href="">Test</a>
</body>
</html>
jQuery
$("a").mouseup(function() {
clearTimeout(pressTimer);
// Clear timeout
return false;
}).mousedown(function() {
// Set timeout
pressTimer = window.setTimeout(function() {
alert("hcbdhaf")
}, 1000);
return false;
}).click(function() {
alert("dfsdg");
});
If your code is really as quoted, the problem is that the elements don’t exist as of when you try to hook event handlers to them. jsFiddle’s default settings hide this problem from you. (Look on the left, and you’ll see that your code isn’t run until the
loadevent fires — which is very, very late in the page load process.)To fix it, either:
Move your script tags to the end of your document, just before or after the closing
</body>tag. By the time the browser runs your script, the elements will exist. This is the recommendation of the YUI team and Google’s web engineers like it too.Use jQuery’s
readyevent.In conjunction with either of those, you might also look at using event delegation instead of directly hooking up events on the elements. Your
mouseupandmousedownhandlers will get attached to eachaelement individually. That’s a lot of hookups. If there’s a container that all of thoseaelements are in (bodyor better yet, something nearer), you might instead hook the event on that container (since those events bubble) and then check to see if the event originated in anaelement. jQuery supports event delegation, doing most of the hard work for you, viadelegate(which I like because it’s so explicit) and more recently, one of the half-dozen variations of arguments you pass toon.