Most of we have seen the most viral button on social media which moves away from the mouse cursor i.e when we hover near the button, button goes away from the mouse pointer. This blog post will guide you and give you the brief concept on how can we achieve the result. To do this task we are using HTML, CSS, Bootstrap and JQuery (Javascript Library). You can simply follow the following steps and can easily make on your own.
Step 1: Create a HTML file on desired location. If you are using visual studio code then you can simply type ! and press enter to get the HTML boiler Plate. This will give you following starting HTML code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
Step 2: Create a button inside the body tag of above html.
<button>Click Me</button>
Step 3: To make this button more beautiful we will use Bootstrap and add some CSS also to handle it with Javascript. To use bootstrap copy the Bootstrap CDN link inside your head tag.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
Also add css above your body tag
<button class = "btn btn-danger">Click Me</button>
<style>
button{
position: absolute;
top:50px;
left:50px;
}
</style>
Step 4: Now you can move the button on mouse hover by using Jquery library. So to use the Jquery library copy the following query can and place it inside the head tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
Also add the script tag below which handles the movement of the button on mouse over.
<script>
$(function(){
$(“button”).on({
mouseover: function(){
$(this).css({
left: (Math.random()*200)+"px",
top: (Math.random()*200)+"px",
});
}
});
});
</script>
Note: you can use ID and Class in button to make button unique
Step 5: Now you are done and open you html file to see a final output.
The final source code to move away button on mouse over is as follow:
<html>
<head>
<title>Funny</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<style>
#readersnepal{
position: absolute;
top:50px;
left:50px;
}
</style>
<body>
<button id= "readersnepal" class = "btn btn-success">Click Me</button>
<script>
$(function(){
$("#readersnepal").on({
mouseover: function(){
$(this).css({
left: (Math.random()*200)+"px",
top: (Math.random()*200)+"px",
});
}
});
});
</script>
</body>
</html>