views:

94

answers:

4

I have this code:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript">
     $(function(){
      $('a.one').click(function(event){
       event.preventDefault();
      });
     });
     function test(event){
      event.preventDefault();
     }
    </script>
    <style type="text/css">
     a.test { font-weight: bold; }
     body { font-family:sans-serif; background-color:#AAAAAA;}
    </style>
</head>
<body>
    <a class="one" href="http://jquery.com/"&gt;jQuery&lt;/a&gt;
    <br/>
    <a class="two" href="http://stackoverflow.com/" onclick='test(event)'>stack overflow</a>
</body>
</html>

The test-function does not work as it stands now, since a regular javascript event doesn't support the jQuery event preventDefault-function. Is there some way to wrap a regular javascript event in a jQuery event so that I can use e.g. preventDefault?

A: 

I think it may be the fact that you're passing event in with onclick='test(event)'. I think onclick='test' is enough. I could be wrong though.

Jimmeh
It's fine. It picks up the `event` global on IE and the `event` argument on other browser and passes it to the function so that it doesn't have to do the usual `if (!e) e= window.event` IE workaround.
bobince
+2  A: 

Try this:

function test(e) {
    $.Event(e).preventDefault();
}

Event object

Darin Dimitrov
A: 

Yes (see Darin's answer). You could also work around IE's lack of preventDefault instead (which is essentially what jQuery is doing):

if ('preventDefault' in event)
    e.preventDefault();
else
    e.returnValue= false;
bobince
A: 

When you just want to execute the javascript - and not redirect - when clicking the href use "return false" in your click function. For example:

$(function(){
        $('a.one').click(function(event){
                var condition = confirm('Do you want to redirect to ...?');
                return condition == true;
        });
});

If you never want the link to redirect use 'javascript:void(0);' as href attribute, all browsers will still render it as a link instead of an anchor (some IE version do this).

Andre Haverdings