In this video, you will learn how to design buttons with magnetic effect on mousemove using HTML, CSS, and Vanilla Javascript. For the buttons, you’re going to use mousemove and mouseout events to perform this magnetic effect.The main attractive functionality of these buttons is that they are magnetic and basically follow the mouse pointer when it moves on the button area and when the mouse leaves the button area it will reset the button transform styles to zero. Hope this video will be helpful when you designing attractive buttons for a website.
Subscribe: https://www.youtube.com/channel/UCNDmzGYwwT3rdY3xQuW8QOA
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Magnetic Buttons | On Mousemove - HTML, CSS & Javascript</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Magnetic Buttons On Mousemove</h1>
<a href="#" class="btn color-01">
<span>Hover Me</span>
</a>
<a href="#" class="btn color-02">
<span>I am Magnetic</span>
</a>
<a href="#" class="btn color-03">
<span>Read More</span>
</a>
<script type="text/javascript">
const btns = document.querySelectorAll(".btn");
btns.forEach((btn) => {
btn.addEventListener("mousemove", function(e){
const position = btn.getBoundingClientRect();
const x = e.pageX - position.left - position.width / 2;
const y = e.pageY - position.top - position.height / 2;
btn.children[0].style.transform = "translate(" + x * 0.3 + "px, " + y * 0.5 + "px)";
});
});
btns.forEach((btn) => {
btn.addEventListener("mouseout", function(e){
btn.children[0].style.transform = "translate(0px, 0px)";
});
});
</script>
</body>
</html>
style.css
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800;900&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body{
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.btn{
position: relative;
text-align: center;
cursor: pointer;
}
.btn span{
position: relative;
display: inline-block;
color: #fff;
font-size: 1.2em;
font-weight: 500;
text-decoration: none;
width: 240px;
padding: 18px 0;
margin: 35px;
border-radius: 8px;
box-shadow: 0 5px 25px rgba(1 1 1 / 15%);
transition: transform 0.15s linear;
}
.color-01 span{
background: linear-gradient(90deg, #EC5C1A, #F6CE61);
}
.color-02 span{
background: linear-gradient(90deg, #0165CD, #55E6FB);
}
.color-03 span{
background: linear-gradient(90deg, #259844, #6FF192);
}
h1{
color: #222;
text-align: center;
margin-bottom: 50px;
font-size: 2.8em;
font-weight: 800;
}
#html #css #javascript