Posts

Showing posts from 2011

Difference in core javascript and jquery event handling

I was surprised to see that jquery handles events in a different way as compared to core javascript event handling. Here is the case jQuery("#testAnchor").click(function() { //do some thing return false; }); If you are returning false in an event handler in jquery, that means you are stopping propagation and preventing default. All the handlers listening on the click event on that element will be called and the event will not be propagated to the parent element. If you use document.getElementById("testAnchor").onclick = function(event) { event = event || window.event; //do some thing return false; returning false in this case wont stop propagating the event. we should indeed say event.cancelBubble= true or event.stopPropagation() based on the browser.

Knowing whether control key is pressed while an event happened

If you are listening to click events of anchors to do some operation of showing a dialog or doing something else, you have to know whether ctrl key is pressed or not as you may not want your custom logic to kick in when ctrl key is pressed as user wants to open the link in the new tab. He is the solution, assuming jquery is used jQuery("a.link").click(function(event) { if(event.metaKey || event.ctrlKey) { //ctrl key is pressed } }); checking for metaKey apart from ctrlKey property of event as mac's command key press will set metaKey property to true and ctrlKey for remaining browsers.

Knowing whether a javascript code is being executed inside an iframe

Sometimes it is required to know whether the code is being executed inside an iframe or not. Following code works for all browsers. var inIframe=false; try { inIframe = window.top.document == document; }catch(ex) { inIframe = true; } The reason for keeping try catch in the above logic is when ever window.top.document is accessed and if that document belongs to different domain, then IE throws Access Denied error.

Accessing state property of xmlhttprequest before readyState 4 in IE

Like IllegalStateException in java, IE also throws Undefined Error when you try to access xmlhttprequest's status property before reaching steady state 4. For example in the following code if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { var status = xmlhttp.status; var isSuccess = status >= 200 && status < 300 || status === 1223 || status === 304; if (xmlhttp.readyState==4 && isSuccess) { alert(xmlhttp.responseText); } }