Search code examples
htmlcssbuttonpositioncursor

Can I change button position depending on the cursor position?


I'm new to javascript yet, so unfortunatelly I'm not aware of the proper commands in it yet. So I have this code, with a button which scrolls back to the top, and I'd like to know if there's a way to change the position of that button depending where the cursor is? For example if the cursor is on the right side of the site, the button appears on the right side. I'm not expecting you to write the code itself if it's long, it's enough if you can tell me what commands I need to use, then I'll try to do it myself

I appriciate any help!

<button onclick="topFunction()" id="topB" title="Go to top">Top</button>



#topB {
display: none; 
position: fixed; 
bottom: 20px; 
right: 30px; 
z-index: 99; 
border: none; 
outline: none; 
background-color: gray; 
color: white; 
cursor: pointer; 
padding: 15px;
border-radius: 10px;
font-size: 18px; 
}

#topB:hover {
color:black;
background-color: red; 
}


window.onscroll = function() {scrollFunction()};

function scrollFunction() {
// After scrolling down "number"px, the button appears
if (document.body.scrollTop >= 10 || document.documentElement.scrollTop >= 
10) {
    document.getElementById("topB").style.display = "block";
} else {
    document.getElementById("topB").style.display = "none";
}
}
function topFunction() {
// Scrolls to the top on click
document.body.scrollTop = 0; 
document.documentElement.scrollTop = 0; 
}

Solution

  • use mousehover event and get the x and y co ordinates of the pointer. now get total width of screen using window.innerWidth now using x position of pointer determine i which half pointer is and change css accordingly. i can help you if you need more help