MirrorMirror
MirrorMirror

Reputation: 188

div onclick only in viewable area

here is the scenario:

<div style="position: absolute; left: 10px; top: 10px; width:50%; height: 50%; border: 1px solid #000000" onclick="alert(0)">
    <textarea style="position: absolute; left: 10px; top: 10px; width:50%; height: 50%; border: 1px solid #FF0000" ondblclick="alert(1)"></textarea>
</div>

The main problem is that the textarea's ondblclick event does not get triggered.

What happens is that if i try to doubleclick in the textarea the div onclick is triggered. I want the onclick of the div to happen ONLY if i click in the area of the div that is not covered by the textarea. How can I achieve that ?

Thanks in advance!

Upvotes: 2

Views: 417

Answers (3)

Robin Maben
Robin Maben

Reputation: 23074

You can use timers to detect intent.

Set a timer when click occurs which will get executed if no subsequent clicks occur.

On double-click clear the timer and execute your default double-click functionality.

As below,

var dblClickIntentTimer = null;

elem.click(function(){
   dblClickIntentTimer = setTimeout(function() {
      //Wait for 100 ms and then execute 'click' functionality here
   }, 100);
});


elem.dblclick(function(){
   clearTimeout(dblClickIntentTimer);

   //Do double-click functionality here  

});

Upvotes: 0

KooiInc
KooiInc

Reputation: 122936

Try reading up on event delegation and adding handlers unobtrusively

Basically you can assign one click or dblclick handler to the div element. Within that handler you can determine the originating element and take the necessary action(s). The links should provide you with further information about that.

edit a basic example (using jquery and one handler function)

Upvotes: 1

MaxArt
MaxArt

Reputation: 22627

Just cancel the event. For traditional event attaching, you have to put return false; in the end, but I'd advice to use some more modern ways to attach event listeners (namely, addEventListener or attachEvent for IE8 and older).

Upvotes: 0

Related Questions