help here div and html functions

Asked

Viewed 85 times

4

I have this code, when I pass the mouse over the div it moves, but I wanted it to happen when I hit the button:

<head>
<style>
    .square{width:100px ;height:100px ;background:red ;transition: all 2s;}

  .square:hover{background:blue;-webkit-transform:translateX(40px);}

 </style>

    <meta charset="utf-8">

  <meta name="viewport" content="width=device-width">

<title>JS Bin</title>

</head>

<body>

<button id="moveRight"> Move Right</button>

<div class="square"></div>

</body>
</html>

2 answers

2

The most direct way to do this is to assign a class with the same style as in hover, and applies it when you click the button.

To make it go back after the two seconds we have the function setTimeout. When this time function runs it is necessary to re-remove the class to restore the original square state:

const quadrado = document.querySelector(".square");

document.getElementById("moveRight").addEventListener("click", function(){
  quadrado.classList.add("mover");//adicionar a classe mover no click
  
  //agora após 2 segundos remove a classe mover que tinha sido adicionada
  setTimeout(() => quadrado.classList.remove("mover"), 2000); 
});
<head>
  <style>
    .square {
      width: 100px;
      height: 100px;
      background: red;
      transition: all 2s;
    }
    
    .square:hover, .mover {
      background: blue;
      -webkit-transform: translateX(40px);
    }
  </style>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <button id="moveRight"> Move Right</button>
  <div class="square"></div>
</body>
</html>

Documentation for the property classList who has the methods add and remove used

  • erases the first answer

  • @zasalamelcorrey You mean the first example is this ? It was not what you intended ?

  • the second already served, erases the first

  • got repetitive

  • @Okay zasalamelcorrey I’ve removed, see if it’s easier for you to understand.

0

You can create a class that will move the div.

In the example below, I replaced the pseudo-class .square:hover by class .mover, which will be added to the div at the click of the button, making it move:

document.getElementById("moveRight").onclick = function(){
  document.getElementsByClassName("square")[0].className += " mover";
};
.square{width:100px ;height:100px ;background:red ;transition: all 2s;}
.mover{background:blue;-webkit-transform:translateX(40px);}
<button id="moveRight"> Move Right</button>
<div class="square"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.