0

I have 2 div's on a page that I want the user to be able to move around with the arrow keys. I tried differentiating them by using focus but too many items(like inputs) can get focus. Currently when I click the div's I am applying a "focused" css style with a dotted line to make it stand out and removing the style from the other div.

.focused{
  border: 1px dashed #cccccc;   
}


$('#tagCommon').click(function(){
  $(this).focus().addClass("focus2");
  $('#tagLatin').removeClass("focus2");
});

I think this will work to intercept the key up events.

So how can I move just the object that has the class of focus2? Something like:

$(document).keydown(function(e) {
    switch (e.which) {
    case 37:
        $('only the div that has class focus2').stop().animate({
            left: '-= 10'
        }); //left arrow key
        break;
    }
});

Thank you very much for bailing me out yet again, Todd

Community
  • 1
  • 1
maddogandnoriko
  • 980
  • 2
  • 13
  • 31

1 Answers1

4

i'm not sure if you still need a solution or not but you can check this one out: http://jsfiddle.net/ft2PD/41/

here is the html

<div id='div1'>
    <input type='text' value='hello' />
</div>

<div id='div2'>
    <label> World</label>
</div>

and here is the javascript:

$(document).ready(function(){
    $('#div1,#div2').click(function(){
        $('div.selected').removeClass('selected');
        $(this).addClass('selected');

    })}).keyup(function(e){
        var div = $('div.selected');
        console.log(div);
        console.log(e.which);            
        switch (e.which) {
    case 37:
        $(div).stop().animate({
            left: '-=10'
        }); //left arrow key
        break;
    case 38:
        $(div).stop().animate({
            top: '-=10'
        }); //up arrow key
        break;
    case 39:
        $(div).stop().animate({
            left: '+=10'
        }); //right arrow key
        break;
    case 40:
        $(div).stop().animate({
            top: '+=10'
        }); //bottom arrow key
        break;
    }
    });​

and last the CSS

#div1
{
    position: absolute;
    width:100px;
    height:100px;
    margin:15px;
    padding:15px;
    border: thin solid #D2D2D2;
}
#div2
{
    position: absolute;
    width:50%;
    margin:15px;
    padding:15px;
    border: thin solid #D2D2D2;
}
.selected
{
    border: 1px dashed #cccccc !important;
}​
Nir
  • 356
  • 1
  • 5