I'm trying to delay creation of each div by 1 sec to no avail, Can't figure out how to use setTimeout or setInterval, any help appreciated.
(also, would like to position divs centered relative to each other).
I'm trying to draw series of them of decreasing sizes, in each other.
Any advice appreciated
var i;
var w = 400;
var delay = 3000;
$(function () {
$("#boom").click(function () {
for (w, i = 0; w >= 20; i++, w = w - 20) {
$('body').append('<div id="div' + i + '" />'); {
if (i % 2 === 0) {
$("#div" + i + "").css({
"background-color": "gold",
"position": "absolute",
"z-index": i,
"top": "20vw",
"left": "20vw",
}).width(w).height(w);
} else {
$("#div" + i + "").css({
"background-color": "chartreuse",
"position": "absolute",
"z-index": i,
"top": "20vw",
"left": "20vw",
}).width(w).height(w);
}
}
}
});
});
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Kwadrat w kwadracie</title>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="boom">Vamos!</button>
<div id="outer"></div>
</body>
</html>
I'm not sure if I exactly understood what is your desired result, but I think this is what you are trying to achieve:
const outerDiv = document.getElementById('outer'),
sizeDecrement = 20;
document.getElementById('boom').addEventListener('click', event => {
let lastDiv = outerDiv,
size = 400;
const interval = setInterval(() => {
const div = document.createElement('div');
div.className = 'inner ' + (size % (2 * sizeDecrement) === 0 ? 'even' : 'odd');
[div.style.height, div.style.width] = [size + 'px', size + 'px'];
lastDiv.append(div);
lastDiv = div;
size -= sizeDecrement;
if (size < sizeDecrement) {
clearInterval(interval);
}
}, 500);
});
.inner {
align-items: center;
display: flex;
justify-content: center;
}
.inner.odd {
background-color: chartreuse;
}
.inner.even {
background-color: gold;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Kwadrat w kwadracie</title>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="boom">Vamos!</button>
<div id="outer"></div>
</body>
</html>
Also, regarding your code: $(function () { is unnecessary, and so is using such an amount of per-div styling instead of creating a class and giving it those styles in style sheet.
See following snippet. I hope it will help
var i = 0;
var w = 400;
var delay = 500;
$(function () {
$("#boom").click(myLoop);
});
function myLoop () {
setTimeout(function () {
$( i === 0 ? 'body' : '#div'+(i-1)).append('<div id="div' + i + '" />');
$("#div" + i + "").css({
"background-color": i % 2 === 0 ? "gold" : "chartreuse",
"position": "relative",
"z-index": i,
"top": i === 0 ? "20vw": "10px",
"left": i === 0 ? "20vw": "10px",
}).width(w).height(w);
i++;
w = w - 20
if (w >= 20) {
myLoop();
}
}, delay)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="boom">Vamos!</button>
<div id="outer"></div>
See fiddle also
Related
I have the logic but I'm confused how to implement it.
The pseudo code of what I need to do is the following:
There is an image array and a counter, set to 0;
1 - When the cursor is initialized, start an interval timer and
monitor the mouse coordinates
2 - When the timer reaches the first interval, display the first image of the array at the actual coordinates of the mouse. Increment the counter.
3 - When the timer reaches the second interval, display the second image of the array at the actual coordinates of the mouse. Increment the counter.
Repeat the task for all images
If the counter == the image array length, reset the counter and start the process again.
For now I have this boilerplate:
let imgArray = [
"https://via.placeholder.com/100",
"https://via.placeholder.com/200",
"https://via.placeholder.com/300",
"https://via.placeholder.com/400"
]
let activeCounter = 0;
function getMouseCoords(e) {
var e = e || window.event;
document.getElementById('container').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
var followCursor = (function() {
var s = document.createElement('img');
s.src= imgArray[activeCounter]
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
}
};
}());
window.onload = function() {
followCursor.init();
document.body.onmousemove = followCursor.run;
}
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
Ideally I'm going to make it in react.js but a plain vanilla JavaScript solution would help me in understanding the code implementation.
Thanks in advance.
If you move the setInterval outside, have the updated x, y values. Try this.
let imgArray = [
"https://via.placeholder.com/100",
"https://via.placeholder.com/200",
"https://via.placeholder.com/300",
"https://via.placeholder.com/400"
]
let index = 0;
let imgArrayLength = imgArray.length;
let x = 0;
let y = 0;
function getMouseCoords(e) {
var e = e || window.event;
x = e.clientX;
y = e.clientY;
document.getElementById('info').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
setInterval(() => {
var img = document.createElement('img');
img.src = imgArray[(index++) % imgArrayLength];
img.style.position = "absolute";
img.style.left = x;
img.style.top = y;
document.getElementById('container').append(img);
}, 2000
);
var followCursor = (function() {
var s = document.createElement('div');
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
s.style.border = '1px solid red';
s.textContent = "🚀"
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
}
};
}());
window.onload = function() {
followCursor.init();
document.body.onmousemove = followCursor.run;
}
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="info"></div>
<div id="container"></div>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
let imgArray = [
"https://via.placeholder.com/100",
"https://via.placeholder.com/200",
"https://via.placeholder.com/300",
"https://via.placeholder.com/400"
]
let count = 0
let index = 0;
let imgArrayLength = imgArray.length;
function getMouseCoords(e) {
var e = e || window.event;
document.getElementById('container').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
var followCursor = (function() {
var s = document.createElement('div');
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
s.style.border = '1px solid red';
s.textContent = "🚀"
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
setInterval(() => {
var s = document.createElement('div');
s.style.position = 'fixed';
s.style.margin = '0';
s.style.padding = '5px';
s.style.border = '3px solid blue';
s.style.top = (e.clientX - 5) + 'px';
s.style.left = (e.clientY - 5) + 'px';
s.style.background = 'blue';
s.style['background-image'] = 'url(imgArray[count])'
document.getElementById('container').appendChild(s)
count++
if(imgArray.length === count)
count = 0
// set the img to position
}, 10000)
}
};
}());
window.onload = function() {
followCursor.init();
document.body.mouseenter = followCursor.run;
}
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
I hope this is what you are expecting...
let imgArray = [
"https://via.placeholder.com/100",
"https://via.placeholder.com/200",
"https://via.placeholder.com/300",
"https://via.placeholder.com/400"
]
let activeCounter = 0;
function getMouseCoords(e) {
var e = e || window.event;
document.getElementById('container').innerHTML = e.clientX + ', ' +
e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}
var followCursor = (function() {
var s = document.createElement('img');
s.id = "imgid"
s.src= imgArray[activeCounter]
s.style.position = 'absolute';
s.style.margin = '0';
s.style.padding = '5px';
setInterval(() => {
activeCounter++
let s = document.getElementById('imgid');
s.src = imgArray[activeCounter]
if(imgArray.length === activeCounter)
activeCounter = 0
// set the img to position
}, 1000)
return {
init: function() {
document.body.appendChild(s);
},
run: function(e) {
var e = e || window.event;
s.style.left = (e.clientX - 5) + 'px';
s.style.top = (e.clientY - 5) + 'px';
getMouseCoords(e);
}
};
}());
window.onload = function() {
followCursor.init();
document.body.onmousemove = followCursor.run;
}
#container {
width: 1000px;
height: 1000px;
border: 1px solid blue;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
class Cell {
constructor(game, index) {
this.isEmpty = false;
this.game = game;
this.index = index;
this.height = (game.height / game.dimension);
this.width = (game.width / game.dimension);
this.id = "cell-" + index;
this.cell = this.createCell();
$("#content").append(this.cell);
if (this.index === this.game.dimension * this.game.dimension - 1) {
this.isEmpty = true;
return;
}
this.setImage();
this.setPosition(this.index)
}
createCell() {
const cell = document.createElement("div");
$(cell).css({
"width": this.height + "px",
"height": this.width + "px",
"position": "absolute",
"border": "1px solid #fff"
})
$(cell).attr("id", this.id);
//On click Move to the Empty Space
$(cell).on("click", () => {
if (this.game.gameStarted) {
let validCells = this.game.checkValidCells();
let compareCells = [];
if (validCells.right) {
compareCells.push(this.game.cells[validCells.right].cell);
}
if (validCells.left || validCells.left === 0) {
compareCells.push(this.game.cells[validCells.left].cell);
}
if (validCells.top || validCells.top === 0) {
compareCells.push(this.game.cells[validCells.top].cell);
}
if (validCells.bottom) {
compareCells.push(this.game.cells[validCells.bottom].cell);
}
let i = this.game.cells.findIndex(item => item.cell === cell);
let j = this.game.findEmptyCell();
if (compareCells.indexOf(cell) != -1) {
[this.game.cells[i], this.game.cells[j]] = [this.game.cells[j], this.game.cells[i]];
this.game.cells[i].setPosition(i);
this.game.cells[j].setPosition(j);
if (this.game.checkWin()) {
alert("you won the game!!");
this.game.numberOfMoves = 0;
this.game.gameStarted = false;
}
this.game.numberOfMoves++;
$("#moves").html("Moves: " + this.game.numberOfMoves);
}
this.game.dragTheTile();
}
})
return cell;
}
setImage() {
const left = this.width * (this.index % this.game.dimension);
const top = this.height * Math.floor(this.index / this.game.dimension);
const bgPosition = -left + "px" + " " + -top + "px";
const bgSize = this.game.width + "px " + this.game.height + "px"
$(this.cell).css({
"background": 'url(' + this.game.imageSrc + ')',
"background-position" : bgPosition,
"background-size": bgSize
})
}
setPosition(index) {
const {left, top} = this.getPosition(index);
$(this.cell).css({
"left": left + "px",
"top": top + "px"
})
}
makeDraggable(index) {
let emptyCellIndex = this.game.findEmptyCell();
$(this.cell).draggable({
containment: "parent",
snap: this.game.cells[emptyCellIndex],
cursor: "move",
snapMode: "inner",
snapTolerance: 20,
helper: "clone",
opacity: 0.5
})
}
makeDroppable(index) {
$(this.cell).droppable({
drop: (event, ui) => {
let draggedCell;
draggedCell = ui.draggable;
let i = this.game.cells.findIndex(item => item.cell === draggedCell[0]);
let j = this.game.findEmptyCell();
[this.game.cells[i], this.game.cells[j]] = [this.game.cells[j], this.game.cells[i]];
this.game.cells[i].setPosition(i);
this.game.cells[j].setPosition(j);
this.game.clearDrag();
this.game.numberOfMoves++;
$("#moves").html("Moves: " + this.game.numberOfMoves);
if (this.game.checkWin()) {
alert("you won the game!!");
this.game.numberOfMoves = 0;
this.game.gameStarted = false;
} else {
this.game.dragTheTile();
}
}
})
}
getPosition(index) {
return {
left: this.width * (index % this.game.dimension),
top: this.height * Math.floor(index / this.game.dimension)
}
}
}
class GameBoard {
constructor(dimension){
this.dimension = dimension;
this.imageSrc = 'https://i.ibb.co/1XfXq6S/image.jpg'
this.cells = [];
let length = Math.min(window.innerHeight, window.innerWidth);
this.width = length - 100;
this.height = length - 100;
this.setup();
this.gameStarted = false;
this.numberOfMoves = 0;
}
setup() {
for(let i = 0;i < this.dimension * this.dimension; i++) {
this.cells.push(new Cell(this, i));
}
}
shuffle() {
for (let i = this.cells.length -1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this.cells[i], this.cells[j]] = [this.cells[j], this.cells[i]];
this.cells[i].setPosition(i);
this.cells[j].setPosition(j);
}
}
findEmptyCell() {
return this.cells.findIndex(cell => cell.isEmpty)
}
checkValidCells() {
const emptyCell = this.findEmptyCell(),
topCell = emptyCell - this.dimension,
leftCell = emptyCell - 1,
rightCell = emptyCell + 1,
bottomCell = emptyCell + this.dimension;
const mod = emptyCell % this.dimension;
let left, right, top, bottom;
if (mod != 0) {
left = leftCell;
}
if (mod != this.dimension -1) {
right = rightCell;
}
if (emptyCell >= this.dimension) {
top = topCell;
}
if (emptyCell < this.dimension * (this.dimension - 1)) {
bottom = bottomCell
}
return {right: right, left: left, top: top, bottom: bottom};
}
findPosition(index) {
return this.cells.findIndex(cell => cell.index === index);
}
checkWin() {
for (let i = 0; i < this.cells.length; i++) {
if (i != this.cells[i].index) {
return false;
}
}
return true;
}
clearDrag() {
this.cells.forEach(cell => {
if($(cell.cell).data('ui-draggable')) $(cell.cell).draggable("destroy");
})
}
dragTheTile() {
this.clearDrag();
const validCells = this.checkValidCells();
let availableCells = [];
if (validCells.right) {
availableCells.push(this.cells[this.findPosition(validCells.right)].index);
}
if (validCells.left || validCells.left === 0) {
availableCells.push(this.cells[this.findPosition(validCells.left)].index);
}
if (validCells.top || validCells.top === 0) {
availableCells.push(this.cells[this.findPosition(validCells.top)].index);
}
if (validCells.bottom) {
availableCells.push(this.cells[this.findPosition(validCells.bottom)].index);
}
let emptyCellIndex = this.findEmptyCell();
availableCells.forEach(cell => {
this.cells[cell].makeDraggable(cell);
this.cells[emptyCellIndex].makeDroppable(cell);
})
}
solve() {
let i;
for (i = 0; i < this.cells.length; i++) {
let j = this.cells[i].index;
if (i != j) {
[this.cells[i], this.cells[j]] = [this.cells[j], this.cells[i]];
this.cells[i].setPosition(i);
this.cells[j].setPosition(j);
i--;
}
if (i === this.cells.length - 1) {
[this.cells[i], this.cells[i - 1]] = [this.cells[i - 1], this.cells[i]];
this.cells[i].setPosition(i);
this.cells[i - 1].setPosition(i - 1);
}
}
}
}
$(document).ready(() => {
let gb;
$("#startGame").on("click", () => {
gb.gameStarted = true;
gb.shuffle();
gb.numberOfMoves = 0;
$("#moves").html("Moves: " + gb.numberOfMoves);
gb.clearDrag();
gb.dragTheTile();
})
$("#solve").on("click", () => {
if (gb.gameStarted) {
gb.solve();
gb.clearDrag();
gb.dragTheTile();
}
})
$("#generate-puzzle").on("click", () => {
let number = parseInt($("#dimension").val());
if(number >= 3 && Number.isInteger(number)) {
gb = new GameBoard(number);
$("#content").css("display", "block");
$("#solve").css("display", "block");
$("#startGame").css("display", "block");
$("#enter-dimension").css("display", "none");
$("#content").css({
width: gb.width + "px",
height : gb.height + "px"
})
} else {
$("#alert").css("display", "block");
}
})
})
body {
background-color: #3d3d3d;
}
#content {
width: 400px;
height : 400px;
background-color: #fff;
margin: auto;
position: relative;
display: none;
}
#startGame {
margin: auto;
display: none;
}
#solve {
margin: auto;
display: none;
}
#alert {
display: none;
}
#moves {
margin: auto;
padding: 5px;
text-align: center;
color: #FFFF00;
}
#enter-dimension {
margin: auto;
}
#label-dimension {
color: #ddd;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- JQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA==" crossorigin="anonymous"></script>
<title>Image Puzzle</title>
</head>
<body>
<div class="container col-md-6">
<div id="moves">
Moves : 0
</div>
<div class="d-flex justify-content-center row">
<div class="col-md-6">
<div class="mt-5" id="enter-dimension">
<form>
<div class="form-group">
<label id="label-dimension" for="dimension">Enter the Dimension of the puzzle</label>
<input type="number" class="form-control" id="dimension">
</div>
<div class="alert alert-danger" id="alert" role="alert">
Enter a Valid Positive Integer Greater than or Equal to 3
</div>
<button type="button" class="btn btn-primary" id="generate-puzzle">Generate the Puzzle</button>
</form>
</div>
</div>
</div>
<div class="row">
<!--The GRid Layout and the tiles -->
<div class="mt-3" id="content">
</div>
</div>
<!--Button to Start the Game -->
<div class="row buttons">
<button type="button" class="btn btn-info mt-2" id="startGame">Start Game</button>
<button type="button" class="btn btn-success mt-2" id="solve">Solve This!</button>
</div>
</div>
</body>
</html>
The puzzle works perfectly but with one issue. If I drag-drop a cell to an empty cell I am unable to drag and drop that tile again to its previous position which is the current empty cell. The way I see it there is a problem somewhere in makeDraggable() and dragTheTile() functions.
When I move a cell with a mouse click I can drag and drop that same cell to its previous position (which is the current empty cell) or If I drag and drop a cell to an empty space I can move it to its previous position (which is the current empty cell) with mouse click. But after dragging the same cell cannot be dragged again. looks like draggable() is disabled for that particular cell.
Once a cell is dragged, The next move it should be a draggable cell (since it is a neighbour cell to the empty cell) When I make it draggable the "ui-draggable" class is added to it but "ui-draggable-handle" class is missing.
The problem was with the function where I cleared the draggable property:
clearDrag() {
this.cells.forEach(cell => {
if($(cell.cell).data('ui-draggable')) $(cell.cell).draggable("destroy");
})
}
The "destroy" method gives some conflicts.
The alternative method I found was to first initialize all the cells with draggable property but disable it in the beginning and enabling it again when I need.
the property used here was "disabled: true" and "disabled: false".
Instead of the dragTheTile() function I wrote a new function called dragTile() as follows:
dragTile() {
this.cells.forEach(cell => {
cell.makeDraggable();
})
const validCells = this.checkValidCells();
let availableCells = [];
if (validCells.right) {
availableCells.push(this.cells[this.findPosition(validCells.right)].index);
}
if (validCells.left || validCells.left === 0) {
availableCells.push(this.cells[this.findPosition(validCells.left)].index);
}
if (validCells.top || validCells.top === 0) {
availableCells.push(this.cells[this.findPosition(validCells.top)].index);
}
if (validCells.bottom) {
availableCells.push(this.cells[this.findPosition(validCells.bottom)].index);
}
let emptyCellIndex = this.findEmptyCell();
availableCells.forEach(cell => {
$(this.cells[cell].cell).draggable({disabled: false});
})
this.cells[emptyCellIndex].makeDroppable(availableCells);
}
This solved the problem very easily.
I'm trying to learn Java Script Animations and I found really good examples on this site: http://javascript.info/tutorial/animation#maths-the-function-of-progress-delta
But the problem is, as a beginner, I don't understand how the functions and objects work with each other.
Question 01
I copied the example "Let’s create a movement animation on it’s base:" But my version does not work.
<!DOCTYPE HTML>
<html>
<head>
<style>
.example_path{
position: relative;
width: 600px;
height: 100px;
border-style: solid;
border-width: 5px;
}
.example_block{
position: absolute;
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
</head>
<body>
<div onclick="move(this.children[0])" class="example_path">
<div class="example_block"></div>
</div>
<script>
function move(element, delta, duration) {
var to = 500
animate({
delay: 10,
duration: duration || 1000, // 1 sec by default
delta: delta,
step: function(delta) {
element.style.left = to*delta + "px"
}
})
}
</script>
</body>
</html>
output console: ReferenceError: animate is not defined
Does anyone know what the problem is?
Question 02
My second wish is, to integrate the easeInOut function
function makeEaseInOut(delta) {
return function(progress) {
if (progress < .5)
return delta(2*progress) / 2
else
return (2 - delta(2*(1-progress))) / 2
}
}
bounceEaseInOut = makeEaseInOut(bounce)
How can I link both code snippets? The code is also from this page: http://javascript.info/tutorial/animation#maths-the-function-of-progress-delta
Add animate and makeEaseInOut into your script tag then you can use them. You may want to include the functions in a separate JavaScript file eventually.
<script>
function animate(opts) {
var start = new Date
var id = setInterval(function() {
var timePassed = new Date - start
var progress = timePassed / opts.duration
if (progress > 1) progress = 1
var delta = opts.delta(progress)
opts.step(delta)
if (progress == 1) {
clearInterval(id)
}
}, opts.delay || 10)
}
function makeEaseInOut(delta) {
return function(progress) {
if (progress < .5)
return delta(2*progress) / 2
else
return (2 - delta(2*(1-progress))) / 2
}
}
bounceEaseInOut = makeEaseInOut(bounce)
</script>
that's what I tried.
I still have problems.
output console: delta is not a function. bounce is not a function.
I know I have to learn more about creating functions. But right now I'm not that good to solve the problem.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.example_path{
position: relative;
width: 600px;
height: 100px;
border-style: solid;
border-width: 5px;
}
.example_block{
position: absolute;
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
<script>
function move(element, delta, duration) {
var to = 500;
animate({
delay: 10,
duration: duration || 1000, // 1 sec by default
delta: delta,
step: function(delta) {
element.style.left = to*delta + "px"
}
});
}
function animate(opts) {
var start = new Date;
var id = setInterval(function() {
var timePassed = new Date - start;
var progress = timePassed / opts.duration;
if (progress > 1) progress = 1
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
}
}, opts.delay || 10);
}
function makeEaseInOut(delta) {
return function(progress) {
if (progress < .5)
return delta(2*progress)/2;
else
return (2 - delta(2*(1-progress)))/2;
};
}
varbounceEaseInOut = makeEaseInOut(bounce);
</script>
</head>
<body>
<div onclick="move(this.children[0], makeEaseInOut(bounce), 3000)" class="example_path">
<div class="example_block"></div>
</div>
</body>
</html>
I've made a very simple animation using javascript, hope it helps, try to "Run code snippet" for better understanding.
/*JavaScript*/
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
function Back() {
var elem1 = document.getElementById("animate");
var id1 = setInterval(frame2, 5);
var pos1 = 350;
function frame2() {
if (pos1 == 0) {
clearInterval(id1);
} else {
pos1--;
elem1.style.top = pos1 + 'px';
elem1.style.left = pos1 + 'px';
}
}
}
/*CSS*/
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
/*HTML*/
<button onclick="myMove()">Click Me</button>
<button onclick="Back()"> roll back</button>
<div id ="container">
<div id ="animate"></div>
</div>
I'm working out a simple jJavascript animation and I use clientX to determine the the position of the animated object, but I get the error above. What am I doing wrong here?
Here is JS code:
(function() {
var pos = 0;
var timer;
var anim = {
time: 100,
obj: null,
init: function () {
anim.obj = document.querySelector('#ball');
anim.obj.style.left = 0 + 'px';
anim.cord();
console.log(document.querySelector('.coordonnee').pageX);
},
cord: function (e) {
if ( parseInt(anim.obj.style.left) >= parseInt(document.body.offsetWidth - anim.obj.offsetWidth) ) {
anim.animBack();
} else {
anim.obj.style.left = parseInt( anim.obj.style.left) + 1 + 'px';
timer = setTimeout(anim.cord, 0.5);
}
anim.myCord(anim.obj.event);
},
animBack: function() {
if ( parseInt(anim.obj.style.left) <= 0 ) {
anim.cord()
} else {
anim.obj.style.left = parseInt( anim.obj.style.left) - 1 + 'px';
timer = setTimeout(anim.animBack, 0.5);
}
},
myCord: function(e) {
var mx = e.clientX;
var y = e.clientY;
console.log(anim.obj.mx);
}
}
anim.init();
})(window);
And the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>JS animation</title>
<style type="text/css">
#ball {
width: 50px;
height: 50px;
background: #ff45ce;
border-radius: 50%;
-webkit-border-radius: 50%;
position: relative;
left: 0;
}
</style>
</head>
<body>
<div id="ball" ></div>
<script type="text/javascript" src="js/animation.js"></script>
</body>
</html>
I tried out your code here in this fiddle .
The error that's coming up here is : TypeError: e is undefined in var mx = e.clientX;
That's because , your event is null or not defined. Redefine your logic for this purpose .
I think the event you are passing is null
anim.object.event is null in this function
anim.myCord(anim.obj.event);
I have a box with text within that scrolling up like the old known marquee tag.
I am using the jquery scrollbox that I found on this website:
http://wmh.github.io/jquery-scrollbox/
now, in my css file I want to replace the ul & il tags with classes, say: .list_wrapper would be instead of ul, and .list would be instead of li, so far so good...
after modifying the css, the scroller stopped to work, i found that i need to modify the "jquery.scrollbox.js" file too, but my knowledge in js is basic.
my page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="/js/jquery.scrollbox.js" type="text/javascript"></script>
<style type="text/css">
#marquee {
height: 180px;
overflow: hidden;
margin: 0;
}
#marquee .list_wrapper {
width: 165px;
line-height: 25px;
list-style-type: none;
padding: 5;
margin: 0;
overflow: hidden;
}
#marquee .list {
overflow: hidden;
}
</style>
<script type="text/javascript">
$(function () {
$('#marquee').scrollbox({
linear: true,
step: 1,
delay: 0,
speed: 65
});
});
</script>
</head>
<body>
<div id="marquee">
<div class="list_wrapper">
<div class="list">• text 1</div>
<div class="list">• text 2</div>
<div class="list">• text 3</div>
<div class="list">• text 4</div>
<div class="list">• text 5</div>
<div class="list">• text 6</div>
</div>
</body>
</html>
heres ths js file (I think there's something to do with the "('ul:first-child') and ('li:first-child'):
/*!
* jQuery Scrollbox
* (c) 2009-2013 Hunter Wu <hunter.wu#gmail.com>
* MIT Licensed.
*
* http://github.com/wmh/jquery-scrollbox
*/
(function($) {
$.fn.scrollbox = function(config) {
//default config
var defConfig = {
linear: false, // Scroll method
startDelay: 2, // Start delay (in seconds)
delay: 3, // Delay after each scroll event (in seconds)
step: 5, // Distance of each single step (in pixels)
speed: 32, // Delay after each single step (in milliseconds)
switchItems: 1, // Items to switch after each scroll event
direction: 'vertical',
distance: 'auto',
autoPlay: true,
onMouseOverPause: true,
paused: false,
queue: null
};
config = $.extend(defConfig, config);
config.scrollOffset = config.direction === 'vertical' ? 'scrollTop' : 'scrollLeft';
if (config.queue) {
config.queue = $('#' + config.queue);
}
return this.each(function() {
var container = $(this),
containerUL,
scrollingId = null,
nextScrollId = null,
paused = false,
backward,
forward,
resetClock,
scrollForward,
scrollBackward;
if (config.onMouseOverPause) {
container.bind('mouseover', function() { paused = true; });
container.bind('mouseout', function() { paused = false; });
}
containerUL = container.children('ul:first-child');
scrollForward = function() {
if (paused) {
return;
}
var curLi,
i,
newScrollOffset,
scrollDistance,
theStep;
curLi = containerUL.children('li:first-child');
scrollDistance = config.distance !== 'auto' ? config.distance :
config.direction === 'vertical' ? curLi.height() : curLi.width();
// offset
if (!config.linear) {
theStep = Math.max(3, parseInt((scrollDistance - container[0][config.scrollOffset]) * 0.3, 10));
newScrollOffset = Math.min(container[0][config.scrollOffset] + theStep, scrollDistance);
} else {
newScrollOffset = Math.min(container[0][config.scrollOffset] + config.step, scrollDistance);
}
container[0][config.scrollOffset] = newScrollOffset;
if (newScrollOffset >= scrollDistance) {
for (i = 0; i < config.switchItems; i++) {
if (config.queue && config.queue.hasChildNodes() && config.queue.getElementsByTagName('li').length > 0) {
containerUL.append(config.queue.getElementsByTagName('li')[0]);
containerUL.remove(containerUL.children('li:first-child'));
} else {
containerUL.append(containerUL.children('li:first-child'));
}
}
container[0][config.scrollOffset] = 0;
clearInterval(scrollingId);
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.delay * 1000);
}
}
};
// Backward
// 1. If forwarding, then reverse
// 2. If stoping, then backward once
scrollBackward = function() {
if (paused) {
return;
}
var curLi,
i,
liLen,
newScrollOffset,
scrollDistance,
theStep;
// init
if (container[0][config.scrollOffset] === 0) {
liLen = containerUL.children('li').length;
for (i = 0; i < config.switchItems; i++) {
containerUL.children('li:last-child').insertBefore(containerUL.children('li:first-child'));
}
curLi = container.children('li:first-child');
scrollDistance = config.distance !== 'auto' ?
config.distance :
config.direction === 'vertical' ? curLi.height() : curLi.width();
container[0][config.scrollOffset] = scrollDistance;
}
// new offset
if (!config.linear) {
theStep = Math.max(3, parseInt(container[0][config.scrollOffset] * 0.3, 10));
newScrollOffset = Math.max(container[0][config.scrollOffset] - theStep, 0);
} else {
newScrollOffset = Math.max(container[0][config.scrollOffset] - config.step, 0);
}
container[0][config.scrollOffset] = newScrollOffset;
if (newScrollOffset === 0) {
clearInterval(scrollingId);
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.delay * 1000);
}
}
};
forward = function() {
clearInterval(scrollingId);
scrollingId = setInterval(scrollForward, config.speed);
};
backward = function() {
clearInterval(scrollingId);
scrollingId = setInterval(scrollBackward, config.speed);
};
resetClock = function(delay) {
config.delay = delay || config.delay;
clearTimeout(nextScrollId);
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.delay * 1000);
}
};
if (config.autoPlay) {
nextScrollId = setTimeout(forward, config.startDelay * 1000);
}
// bind events for container
container.bind('resetClock', function(delay) { resetClock(delay); });
container.bind('forward', function() { clearTimeout(nextScrollId); forward(); });
container.bind('backward', function() { clearTimeout(nextScrollId); backward(); });
container.bind('speedUp', function(speed) {
if (typeof speed === 'undefined') {
speed = Math.max(1, parseInt(config.speed / 2, 10));
}
config.speed = speed;
});
container.bind('speedDown', function(speed) {
if (typeof speed === 'undefined') {
speed = config.speed * 2;
}
config.speed = speed;
});
});
};
}(jQuery));
thank you!
open jquery-scrollbox.js and try to change by the hand (not automatically) all ul&li tag on div tag