Elfayer
Elfayer

Reputation: 4561

How to manage events on a specific div?

I would like to catch some events for a specific div if the user clicked on the div (focus the div), keyboard events are catch (not if the last click was out of the div (unfocus the div)

I tried some things, but haven't succeeded : JSFiddle

document.getElementById("box").onkeydown = function(event) {
    if (event.keyCode == 13) { // ENTER
        alert("Key ENTER pressed");
    }
}

This code doesn't work even if I click on the div.

Pure JS solution please

Upvotes: 1

Views: 84

Answers (4)

Gian Carlo
Gian Carlo

Reputation: 215

try this code i hope this work

var mousePosition = {x:0, y:0};
document.addEventListener('mousemove', function(mouseMoveEvent){
  mousePosition.x = mouseMoveEvent.pageX;
  mousePosition.y = mouseMoveEvent.pageY;
}, false);

window.onkeydown = function(event) {
    var x = mousePosition.x;
    var y = mousePosition.y;

    var elementMouseIsOver = document.elementFromPoint(x, y);
    if(elementMouseIsOver.id == "box" && event.keyCode == "13") {
        alert("You Hate Enter Dont You?");    
    }
}

DEMO

Upvotes: 1

Marvin
Marvin

Reputation: 559

Giving the 'div' a tabindex should do the trick, so the div can have the focus:

<div id="box" tabindex="-1"></div>

If you click on the div it gets the focus and you can catch the event.

JSFIDDEL

If you set 'tabindex' > 0 you can also select the div using TAB.

Upvotes: 1

gitaarik
gitaarik

Reputation: 46350

You could catch all the click events, then check if the event target was inside the div:

var focus_on_div = false;

document.onclick = function(event) {
    if(event.target.getAttribute('id') == 'mydiv') {
        focus_on_div = true;
    } else { 
        focus_on_div = false;
    }
}

document.onkeyup = function(event) {
    if (focus_on_div) {
        // do stuff
    }
}

Upvotes: 1

James Donnelly
James Donnelly

Reputation: 128776

The div element isn't interactive content by default. This means that there isn't a case where the return key will ever trigger on it. If you want your div element to be interactive you can give it the contenteditable attribute:

<div id="box" contenteditable></div>

In order to now fire the event you need to first focus the div element (by clicking or tabbing into it). Now any key you press will be handled by your onkeydown event.

JSFiddle demo.

Upvotes: 3

Related Questions