JSFiddle - React, Tailwind, and code Playground

by Olayinka Otuniyi

HTML

<input type='button' value='up' onclick='up()'/>
<input type='button' value='down' onclick='down()'/>
<input type='button' value='left' onclick='left()'/>
<input type='button' value='right' onclick='right()'/>
<input type='button' value='Run' onclick='Run()'/>

<div id="square"></div>

CSS

#square{
  
  width: 50px;
  height: 50px;
  background-color: blue;
    position: relative;
  animation: myfirst 5s linear 2s infinite alternate;
  
}

JavaScript

var moves = [];
leftpx = 0;
downpx = 0;
uppx = 0;
rightpx = 0;
var up = function() {

    moves.push('up')

}

var down = function() {

    moves.push('down')

}

var left = function() {

    moves.push('left')

}

var right = function() {

    moves.push('right')

}
 document.addEventListener("moveRight", function(e) {
  console.log(e.detail); // Prints "Example of an event"
 // document.getElementById('square').style.left = 
myMove4(100);
});
document.addEventListener("stopRight", function(e) {
  console.log(e.detail);
clearInterval(e.detail);
  // Prints "Example of an event"
 // document.getElementById('square').style.left = 
//myMove4(100);
});

var Run = function() {
// Add an event listener
// document.addEventListener("name-of-event", function(e) {
  // console.log(e.detail); // Prints "Example of an event"
// });

// Create the event

    for (var i = 0; i < moves.length; i++) {

        if (moves[i] == 'up') {
            document.getElementById('square').style.top = setInterval(myMove(), 3000);
        };
        if (moves[i] == 'left') {
            document.getElementById('square').style.left = myMove3()
        };
        if (moves[i] == 'down') {
            document.getElementById('square').style.top = myMove2()
        };
        if (moves[i] == 'right') {
           // rightpx = rightpx + 100;
		  

// Dispatch/Trigger/Fire the event
if (r) return;
var r= setInterval(function(){
	var event = new CustomEvent("moveRight", { "detail": "Example of an event" });
	document.dispatchEvent(event)
		var event1 = new CustomEvent("stopRight", { "detail": r });
	document.dispatchEvent(event1);},300);

           // document.getElementById('square').style.left = setInterval(myMove4(100),3000);
        };
    }
    moves = [];
}

function myMove() {
    var elem = document.getElementById("square");
    var pos = 0;
    var id = setInterval(frame, 5);

    function frame() {
        if (pos == -100) {
            clearInterval(id);
        } else {
           ...