Monday, January 18, 2010

How to retrieve text content from a div

In the following HTML

<div id='mydiv'>Some Text </div>

To retrieve the text using javascript - this is one method there may be others

var mydiv=document.getElementById('mydiv');

if (mydiv.textContent)
alert(mydiv.textContent); // for IE
else
alert(mydiv.innerText); // everyone else

Wednesday, January 13, 2010

Handling click and double click on the same object

There is a problem if you want to handle both click and double click events on an html element.
Basically both the click and double click events get fired when the user double clicks when really you want one event or another.

At first I tried handling the double click by counting single click and not setting a double click event. This worked on firefox but not internet explorer(because only one click was triggered for a double click).

I solved the problem by handling both the double click and click events. Basically When the mouse is clicked a timer is set up to insure that double click was not fired. If double click is fired then single click is canceled, otherwise the click function fires.

Heres the code
function mousefunctions(){
}

mousefunctions.singleclick=function(){
clickcount=0;
alert('single click');
}

mousefunctions.doubleclick=function(){
clickcount=0;
alert('doublelick');
}
var clickcount=0;


mousefunctions.endtimer=function(){
if(clickcount==1){
mousefunctions.singleclick();
}
}

mousefunctions.handledbclick=function(){
mousefunctions.doubleclick();
}


mousefunctions.handleclick=function(){
if(clickcount==0)
setTimeout(mousefunctions.endtimer,300);
clickcount++;

}

And the HTML is
<div onclick="mousefunctions.handleclick();"ondblclick="mousefunctions.handledblclick();" >Some Text</div>