Harsh
Harsh

Reputation: 70

Javascript Animation Highlight

When we execute this code, a small box appears at the top left corner of a big box at start and at the end it is at the bottom right corner of the big box and i want that a diagonal line must be shown from the top left corner to the bottom right corner since it is the path traveled by the small box(or i can say i want to highlight the path traveled by the small box) . Can someone help me with this ?

function slider()
{
    var t=setInterval(display,3);
    var pos=0;
    var x=document.getElementById("a1");
    function display()
    {
        if(pos==350)
            clearInterval(t);
        else
        {
            pos++; 
            x.style.top=pos+'px';
            x.style.left=pos+'px';
        }
    }
}
h2{
    font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, 
    sans-serif;
    text-align: center;
    font-size: 50px; 
    color: rgb(100, 158, 13);
    background-color: bisque;
    border: 5px red groove;
}

body{
    background-color: cornflowerblue;
}

.container{
    background: black;
    height: 400px;
    width: 400px;
    position: relative;  
}

.box{
    background: whitesmoke;
    height: 50px;
    width: 50px;
    position: absolute;
 }
<h2>This is my first animation code</h2>
<center>
<div class="container">
    <div id="a1" class="box">
    </div>
</div>
<p>
    <button type="button" onclick="slider()">click here</button>
</p> 
</center>

Upvotes: 2

Views: 294

Answers (1)

Takit Isy
Takit Isy

Reputation: 10081

CSS is not really made for that but…

… You could fake this effect, using another element:

function slider() {
  var t = setInterval(display, 3);
  var pos = 0;
  var a1 = document.getElementById("a1");
  var path = document.getElementById("path");

  function display() {
    if (pos == 350)
      clearInterval(t);
    else {
      pos++;
      a1.style.top = pos + 'px';
      a1.style.left = pos + 'px';
      path.style.height = pos + 'px';
      path.style.width = pos + 'px';
    }
  }
}
body {
  background-color: cornflowerblue;
}

.container {
  background: black;
  height: 400px;
  width: 400px;
  position: relative;
}

.box {
  position: absolute;
  background: whitesmoke;
  height: 50px;
  width: 50px;
}

#path {
  position: absolute;
  height: 0;
  width: 0;
  margin: 25px;
  background: linear-gradient(to top right, transparent 49%, red 50%, transparent 51%);
}
<div class="container">
  <div id="path"></div>
  <div id="a1" class="box"></div>
</div>
<button type="button" onclick="slider()">click here</button>

Of course, if you want the box to move again after that first move, you must use another element, and so on…

Hope it helps.

Upvotes: 1

Related Questions