Monday, May 20, 2024
144
rated 0 times [  147] [ 3]  / answers: 1 / hits: 9071  / 11 Years ago, mon, december 23, 2013, 12:00:00

I'm trying to get the following code to work in all versions of IE, as it works find in other browsers:



  <a href= class=specificClass>Click Me </a>
//Javascript
$(.specificClass).click(
function(e) {
e.preventDefault();
// Do Something
//return false; Doesn't work either
}
);


Switching to href=# makes it try to go to the top of the page, again only in IE9. For example:
Leaving href= redirects to the current link itself in IE9.



<a href=# onclick=doSomething(this); return false;> Click Me Two </a>


It seems like both approaches triggers the onclick Javascript to be called, but the default behavior for href= is not getting overridden. If I use event.preventDefault() nothing happens.



The below approach works:



<a href=javascript:doSomething(this);> Click Me Two </a>
function doSomething(me) {

// event.preventDefault is not needed as the javascript is added via href

}


However I don't want to have href=javascript: or onclick =doSomethingfor all my anchor tags just to get it to work in IE9.
I also don't want to use a different tag (tried the span tag for example) since it is tricky to style up in all browsers.



Any other ideas?



Looks like it is a legit bug, I have submitted a request to fix it. I have also put in a workaround for now:
https://connect.microsoft.com/IE/feedback/details/812247/event-preventdefault-or-return-false-dont-work-in-ie9


More From » cross-browser

 Answers
1

In IE9 the legacy event handler model is still partial used. preventDefault() works only, when the event listener is attached using addEventListener().



If you want to prevent default action from an inline handler, you have to use the legacy method:



event.returnValue = false;
event.cancelBubble = true; // This is affects like event.stopPropagation() in older IEs


Though jQuery not working is odd, I've no explanation for that... Unless you're running IE in compatible mode and use jQuery 2.X?






EDIT



Also a reference to console object will break the code in IE<10, if Dev Tools are not opened. You can find a lot of fixes for this problem at SO. My favorite is this:



// The very first lines in the global context
if (!window.console) {
window.console = {
log: function () {}
// Add other console methods, if the scripts on the page are using them
}
}


Though the console problem can be avoided with the code above, it's always better to remove all loggings from the final code to be published.


[#49268] Sunday, December 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hayleevalenciac

Total Points: 164
Total Questions: 89
Total Answers: 106

Location: Burkina Faso
Member since Thu, Dec 15, 2022
1 Year ago
;