div boundary jQuery -


http://jsbin.com/ofudi4/3/edit

what code can test yourselves.

now question if have div-tag around , frame. how make #moveme move inside frame div? checking boundaries after each move, figure doesn't move outside frame.

anyone how to?


edit: adding code link.

$(document).keydown(function(e){     // left     if (e.keycode == 37) {        $("#moveme").animate({marginleft: "-=100px"}, {queue:false});        return false;     }     // top     if (e.keycode == 38) {        $("#moveme").animate({margintop: "-=100px"}, {queue:false});        return false;     }     // right     if (e.keycode == 39) {        $("#moveme").animate({marginleft: "+=100px"}, {queue:false});        return false;     }     // bottom     if (e.keycode == 40) {        $("#moveme").animate({margintop: "+=100px"}, {queue:false});        return false;     } }); 

html

<body>   <div id="moveme"></div> </body> 

if change animating margin animating left , top it's easier test conditions using .position()

test if it's less 0 or greater parent width/height - it's width/height.

if not, animate usual, if set to edge.

you should changing easing, movement bit odd when hold down.

if (e.keycode == 37) {    if($("#moveme").position().left >= 100)   {    $("#moveme").animate({left: "-=100px"}, {queue:false});   }   else   {    $("#moveme").animate({left: 0}, {queue:false});   }    return false; }  if (e.keycode == 39) {    if($("#moveme").position().left <=        $("#moveme").parent().width() - $("#moveme").width() - 100)   {      $("#moveme").animate({left: "+=100px"}, {queue:false});   }   else   {      $("#moveme").animate(        {left: $("#moveme").parent().width() - $("#moveme").width()},        {queue:false});   }    return false; } 

http://jsbin.com/ofudi4/5


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -