views:

343

answers:

3

I am implementing a floating pop-up help control in an asp.net web site, and i'm using JQuery to implement the whizzy bits.

The pop up is made visible by clicking on a link, the link also has an href poining to another page to support users with JavaScript disabled. I added "return false;" to the end of the Javascript string in the onClick event of the link, to prevent Navigation to the href value, and was very happy until I realised that this is not supported in Firefox.

I've come across several articles pointing to the event.preventDefault method that can be used to get Firefox to behave in the same way, but in all cases the example involved seems to have some onerous pattern of explicitly adding events to the object concerned.

Is there a simple way to get this kind of syntax to work? I want to keep my control as simple as possible. Code example:

<a id="myLink" 
onclick="javascript:$('#myPanel').addClass('helpPopOn');return
false;" href="/pages/help.aspx?content=TestHelp">Help</a>
+5  A: 

Explicitly adding events is onerous?

$("#myLink").click(function(e)
{
   $('#myPanel').addClass('helpPopOn');
   e.preventDefault();
});
Shog9
Thanks - how would I integrate this in to my control though? There may be multiple of this same control so I need to be able to pass in control ID etc?
the Zapper
What DOM elements is your "control" composed of? I see you currently using two IDs, so those would need to be different for each control; if they can be easily associated in the DOM without explicit IDs, then you could use class names, etc... Check out the design of other jQuery controls.
Shog9
+1  A: 

While Shog9's answer is correct, for completeness the same logic obviously also applies to inline handlers:

<a id="myLink" onclick="javascript:$('#myPanel').addClass('helpPopOn');event.preventDefault();return false;" href="/pages/help.aspx?content=TestHelp">Help</a>
olliej
A: 

The answers so far either haven't quite done what I wanted, or didn't seem to work cross-browser. In the end, the following seems to be a compromise:

<a id="myLink" onclick="javascript:if (event.preventDefault) event.preventDefault();$('#myPanel').addClass('helpPopOn');return false;" href="/pages/help.aspx?content=TestHelp">Help</a>

Note the prevent default at the beginning, and the return false at the end. This seems to works across IE, Opera, Safari, and in Firefox it semi-works (the div will pop-up once, but not again). Anybody know how to get this working properly in FireFox?

the Zapper