Reputation: 23
As the title says, I am looking for an efficient way to move a button when the mouse is moved over it (just for a little project I'm working on). I decided on using jQuery, but I am running into trouble with the code below. As it is syntactically correct (I believe), no errors are being thrown, but the button is not being moved as intended. Any help would be greatly appreciated, thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src = "jquery.js"></script>
<title>Click The Button!</title>
</head>
<body>
<input type="button" value="Try and Click Me!">
<script>
$("input").mouseenter(function(){
$(this).style.position = "absolute";
$(this).style.left = Math.floor(Math.random()*600)+"px";
$(this).style.top = Math.floor(Math.random()*400)+"px";
});
</script>
</body>
</html>
Obligatory edit to thank all those who replied for their correct responses! Much appreciated.
Upvotes: 2
Views: 178
Reputation: 111
Change your input to add an id:
<input id="mybutton" type="button" value="Try and Click Me!">
Then you can access the button
<script>
$("#mybutton").mouseenter(function(){
$(this).css({
position: "absolute",
left: Math.floor(Math.random()*600)+"px",
top: Math.floor(Math.random()*400)+"px"
});
});
</script>
Upvotes: 0
Reputation: 15148
Give this a shot:
$("input").mouseenter(function () {
$(this).css({
"position":"absolute",
"left": Math.floor(Math.random() * 600) + "px",
"top": Math.floor(Math.random() * 400) + "px"
});
});
Here is a fiddle
Upvotes: 1
Reputation: 282
$("input").mouseenter(function(){
$(this).css({left:Math.floor(Math.random()*600)
,top:Math.floor(Math.random()*600)
,position:"absolute"});
});
Upvotes: 0
Reputation: 94439
When dealing with a jQuery Object such as $(this)
use the css
function to adjust CSS properties. Using element.style.left
and etc is used when accessing the properties of a native DOM element, not an element selected with jQuery.
$("input").mouseenter(function(){
$(this).css("position","absolute");
$(this).css("left", Math.floor(Math.random()*600)+"px");
$(this).css("top",Math.floor(Math.random()*400)+"px");
});
JS Fiddle: http://jsfiddle.net/5LWAk/
Upvotes: 3