Labels

Showing posts with label JS-Tricks. Show all posts
Showing posts with label JS-Tricks. Show all posts

Monday, April 7, 2008

Event Handling - IE & FFox

Hi,

This blog post summarizes the Event Handling in IE and Ffox. My experience – Its very confusing and iratic.

Event Object Detection:

There are lots of ways been given on google to do this. I found below to be very simple instead of doing it in my earliar post.

The best way to do this is as below.

function CheckKey(myEvent)

{

if(!myEvent) // Null for IE

{

myEvent = window.event;

}

}

Event Passing:

Fucntion Call

IE

FF

document. onkeydown= CheckKey;

Event not Passed

Event Passed

(Automatically)

document. onkeydown = function(event){CheckKey(event);}

Event not Passed

Event Passed

<input type='text' id='entry' onkeydown ='CheckKey();' />

Event not Passed

Event not Passed

<input type='text' id='entry' onkeydown ='CheckKey(event);' />

Event Passed

Event Passed

function CheckKey(myEvent)

{

if(!myEvent)

{

myEvent = window.event;

alert('Event not Passed');

}

else

{

alert('Event Passed');

}

}

Event Cancel Bubbling:

There are lots of ways been given to cancel the event bubbling. But to be very honest, its luck if they work for you. I deveised a simple way of doing it in IE & Ffox.

In the below example, the action Ctrl-P (print) is cancelled.

function CheckKey(myEvent)

{

var Mozilla = myEvent;

if(!myEvent)

{

myEvent = window.event;

}

if(myEvent.ctrlKey)

{

if(myEvent.keyCode == 80)

{

if(!Mozilla) // IE

{

myEvent.keyCode = 505;

return false;

}

Else

{

return false; // Ffox

}

}

}

}

Note:

//myEvent.cancelBubble = true; // Does not work

//myEvent.returnValue = false; // Does not work

Event Properties Equivalence:

Below table summarizes the property name in IE and its equivalent in Ffox.

Not necessarily this will work all the time. J

Properties

FFox Equivalent?

Description

keyCode

Same (For KeyDown, KeyUp)

charCode (Only for KeyPress).

Property indicating the Unicode for the key pressed. Use String.fromCharCode(keyCode) to convert code to string.

altKey, ctrlKey, shiftKey, metaKey

Same.

Boolean properties that indicate whether the Alt, Ctrl, and Shift keys were pressed at time of the event.

clientX, clientY

Same.

Returns the mouse coordinates at the time of the event relative to upper-left corner of the window. Example(s).

type

Same.

A string indicating the type of event, such as "mouseover", "click", etc.

srcElement

target

The element in which the event occurred on.

offsetX, offsetY

N/A

Returns the mouse coordinates relative to the originating element.

button

Same, but different return values.

An integer indicating which mouse button was pressed or released, 1 = left, 2 = right, 4 = middle. If multiple buttons are pressed, the value is the sum of both buttons, such as 3 (1+2) for left and right.

cancelBubble

stopPropagation()

Set to true to prevent the event from bubbling.

fromElement, toElement

relatedTarget

For mouseover and mouseout events, these properties indicate the elements the mouse is leaving from and moving onto, respectively.

returnValue

preventDefault()

Set to false to cancel any default action for the event.

Hope this helps.

Thanks & Regards,

Arun Manglick || Tech Lead


Friday, December 14, 2007

Display vs Visibility

Showing and hiding a dialog box

Showing or hiding an element can be done by

  • Setting its display property to none or
  • Setting its visibility to hidden.

Display: An element whose display is set to none does not consume space in the layout i.e. the layout of the rest of the element is done as if this element did not exist at all.

Visibility: An element whose display is set to hidden the element is still layed out but it is not shown i.e. the element consumes space. Hence an invisible element still affects the layout.


document.getElementById("DivContent").style.display='none';
and
document.getElementById("DivContent").style.display='block'

Thanks & Regards,

Arun Manglick || Tech Lead

Wednesday, December 5, 2007

Display/Visible styling property in JS

Hi,

Here, is the fact that Display/Visible styling property in JS works perfectly in IE and Firefox.

Display

· Block

· None

Visiblilty

· Visible

· Hidden

function Hide1()

{

//debugger;

obj=document.getElementById('divHidden');

if(obj.style.display == "")

{

obj.style.display='none';

}

else

{

obj.style.display='';

}

}

function Hide2()

{

obj=document.getElementById('divHidden');

if(obj.style.visibility == "")

{

obj.style.visibility='hidden';

}

else

{

obj.style.visibility='';

}

}

Thanks & Regards,

Arun Manglick || Tech Lead

Friday, July 6, 2007

Prevent Enter Key

function noenter(e){

     var keycode = null;

     keycode = e==null ? event.keyCode : e.which;

     /*OR

     if (e == null) { // ie

     keycode = event.keyCode;

     } else { // mozilla

     keycode = e.which;

     }*/

     return (13 == keycode);

}

 

 

function CheckEnterKey()

{          

                        if (event.keyCode == 13)

                        {                                                                      

                                    window.event.returnValue = null;

                        }                                  

}

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Tuesday, June 26, 2007

JavaScript - cross-browser ambiguities

Writing cross-browser JavaScript can be a tedious task, especially if you are new to it. The problems arise because JavaScript interpreters included in the browsers implement some of the language features differently.

Following are some of the common discrepancies between IE and Mozilla Firefox –

 

The event object: Whenever you move the mouse, click, press a key, etc., an event is fired. In IE this event is global; it's stored in window.event.

In Firefox, and other browsers, this event is passed to whatever function is attached to the action.

Take a look at the following code fragment -

 

document.onmousemove = mouseMove;

function mouseMove(ev){

          ev = ev || window.event;

          var target = ev.target || ev.srcElement;

}

 

Since we attached the mouseMove function to document.onmousemove, mouseMove gets passed the event object. To make ev contain the event object in every browser we OR it with window.event.

 

Also, IE stores the target element of the event in window.event.srcElement whereas Firefox stores it in ev.target. So to get the target of the event, we use ev.target || ev.srcElement.

 

Mouse Coordinates: Firefox and other browsers use event.pageX and event.pageY to represent the mouse position relative to the document. If you have a 500x500 window and your mouse is in the middle, pageX and pageY will both be 250. If you then scroll down 500 pixels pageY will now by 750. Contrary to this, MSIE uses event.clientX and event.clientY to represent the mouse position relative to the window, not the document. In our same example clientX and clientY will both be 250 if you put your mouse at the middle of a 500x500 window. If you scroll down on the page, clientY will remain 250 since it is measured relative to the window and not where you are on the document.

 

As a result we need to add the scrollLeft and scrollTop properties of the document body to our mouse position.

 

if(ev.pageX || ev.pageY){

     return {x:ev.pageX, y:ev.pageY};

}

var mouseCoords = { x:ev.clientX + document.body.scrollLeft, y:ev.clientY + document.body.scrollTop };

 

InnerText of an item: Firefox  uses element.textContent whereas IE uses element.innerText.

 

var text = element.innerText || element.textContent

 

Adding opetions to Select element:

To add to the options[] array of an html Select the standard method is selectObject.add(option,before); where option is the option to add and before indicates where to insert the new option (null indicates that the new option will be inserted at the end of the list)

But IE uses selectObject.add(option) implementation. So to get around it use the following code –

try

{ selectObject.add(y,null); // standards compliant }

catch(ex)

{ selectObject.add(y); // IE only }

 

Conclusion: The disadvantage of the approaches mentioned above is that these conditional code fragments are spread all over your application’s JavaScript code. For a better code organization consider wrapping the fragments that deal with cross-browser discrepancies in a set of functions and use them in your code.

 

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

Drag Drop using javascript

Note : There are two files attached with this – You can Download them from Yahoo.

 

Introduction

 

I have been working on a requirement to implement drag-drop functionality in a web application using JavaScript. Though there are many JavaScript libraries like scriptaculous which support many flavors of drag-drop, it’s always fun to write your own which does things the way you want.

Here I am attaching the JavaScript file, DragDropJScript.js, which implements the drag-drop along with a sample application.

 

How to make it work

 

1) Link the DragDropJScript.js file with your aspx page.

 

<script type="text/javascript" src="DragDropJScript.js"></script>

 

2) Create two DIV elements on your page; one will act as the source of draggable items and the other as the drop-target. Add arbitrary items to the drag source DIV.

 

<div id="DragContainer" .. and <div id="DropContainer">

 

3) Call the JavaScript function CreateContainers(). Pass the Ids of both the DIVs to it. This will mark the containers as drag-source and drag-container. You can call CreateContainers on any suitable client-side event like window.onload.

 

window.onload = function(){

CreateContainers("DragContainer", "DropContainer"); ...

}

 

4) Implement the OnItemDrop() method. This method is called by the code in DragDropJScript file when a valid item is dragged from the drag-source container and dropped in the drop-target container. Use this method to do your own processing such as doing an asynchronous callback to the server.

 

function OnItemDrop(approved, item, dropTarget){ ...

 

5) The asynchronous callback can be implemented by using ICallBackEventHandler as I have done in the sample. Please refer to MSDN documentation for more on ICallBackEventHandler.

 

6) Process the results of the callback and take appropriate action on the page. In the sample, this is done through ShowModifiedCart function.

 

Known Issues

 

1) The drag effect may not be displayed properly in case of Mozilla firefox browser.

2) It currently supports only one pair of container on one page.

 

Important: You can use the DragDropJScript.js file in your code. But in case you make any modifications to it please post the modified file on the forum.

 

Let know if you need any clarifications of have any suggestions.

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.