help here div and html functions

4

I have this code, when I hover 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>
    
asked by anonymous 04.11.2017 / 01:02

2 answers

2

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

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

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 that has the add methods % and% used%

    
04.11.2017 / 01:15
0

You can create a class that will move div .

In the example below, I replace the pseudo-class .square:hover with the class .mover , which will be added to 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>
    
04.11.2017 / 03:34