<html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> <style> #contenedor{ background-color: lightblue; width:500px; height:600px; padding:10px; border:10px solid blue; position:relative; } .elemento{ background-color: red; border: solid 1px black; display:inline-block; box-sizing: border-box; } .pelota{ background-color: red; border: solid 1px black; position:absolute; top:0; left:0; box-sizing: border-box; border-radius: 50%; width:50px; height:50px; } </style> </head> <body style="background-color:lightgrey"> <input type="number" id="incremento" value="10"> <input class="btn btn-info boton" type="button" id="cambiar" value="Cambiar"> <input class="btn btn-info boton" type="button" id="pelota" value="Pelota"> <div id="contenedor"> </div> <script> $(function () { var incX=10; var incY=10; $('#cambiar').click(function () { var incremento = Number($('#incremento').val()); $('#contenedor').width($('#contenedor').width() + incremento) .height($('#contenedor').height() + incremento); }); $("#contenedor").mouseover(function (e) { console.log(e); }); $('#pelota').click(function(){ $("#contenedor").append("<div class='pelota'></div>"); setTimeout(moverPelota,100); }) function moverPelota(){ $(".pelota").css("top","+="+incY+"px"); $(".pelota").css("left","+="+incX+"px"); var top=parseInt($(".pelota").css("top")); var left=parseInt($(".pelota").css("left")); var ancho=$('#contenedor').width()-$(".pelota").outerWidth()/2; var alto=$('#contenedor').height()-$(".pelota").outerHeight()/2; if (top>alto || top<0){ incY=-incY; } if (left>ancho || left<0){ incX=-incX; } setTimeout(moverPelota,100); } }); </script> </body> </html>