-5

I want a button to move to a new position when you hover over it and it stays there. Sort of like the button is scared of the mouse. Preferably with vanilla JS and CSS

button{
  position: absolute;
  top: 10px;
  left: 10px;
}

button:hover{
  left: 200px;
  top: 200x;
}
<button>button</button>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
dez03
  • 1
  • 1
  • 1
  • What's wrong with the code you have? – Scott Marcus Feb 15 '21 at 19:50
  • You'd have more fun/power with javascript behind it. On mouse over you can delete element insert it else where in the HTML and use CSS to style all the div/trap areas haha. – BGPHiJACK Feb 15 '21 at 19:51
  • Please define behaviour exactly, i.e. conditions of "stay there" and if there is only one static _refugium_. Currently it stays at this single alternative position as long as the (mouse-)pointer sticks hovering over the initial position. – hc_dev Feb 15 '21 at 20:02
  • The button is not afraid. If the button moves to the right side when you hover, you no longer hover on the button and the button goes back to the beginning. Because it happens so fast, it looks like the button is blinking. If you want to do this right, you have to use JavaScript. – GucciBananaKing99 Feb 15 '21 at 20:03
  • [solution](https://stackoverflow.com/a/19962658/10764341https://stackoverflow.com/a/19962658/10764341)..... Whisper:: I like G-Cyrillus method though.... – Ashish Bhattarai Feb 15 '21 at 21:02

2 Answers2

3

const button = document.getElementById('btn');
button.addEventListener('mouseover', function () {
    button.style.left = `${Math.ceil(Math.random() * 90)}%`;
    button.style.top = `${Math.ceil(Math.random() * 90)}%`;
});
button.addEventListener('click', function () {
    alert('you clicked me')
})
#btn {
            position: absolute;
            transition: .5s;
            background-color: dodgerblue;
            padding: 10px;
            height: 40px;
            width: 150px;
        }
<button id="btn">Click me if you can</button>
Indrakant
  • 361
  • 3
  • 9
0

you could give a hudge transition delay, it will look like freezed and las almost an eternity on a webpage. but used only once, to make the button move around, javascript will be needed.

CSS example

button{
  position: absolute;
  top: 10px;
  left: 10px;
  transition:0s 20000s ;
}

button:hover{
  left: 200px;
  top: 200x;
  transition:0s 0s;
}
<button>button</button>
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129