more chaotic upward movement - javascript

I have a heart movement on my page starting from the bottom of the page. Each randomly generates the size and speed of movement.
How can I make them, instead of appearing at the bottom of the page, appear when you click on the specified place, and move not evenly, but more chaotically and disappear before reaching the end?
var love = setInterval(function() {
var r_num = Math.floor(Math.random() * 40) + 1;
var r_size = Math.floor(Math.random() * 30) + 10;
var r_left = Math.floor(Math.random() * 100) + 1;
var r_time = Math.floor(Math.random() * 5) + 5;
$('.bg_heart').append("<div class='heart' style='width:" + r_size + "px;height:" + r_size + "px;left:" + r_left + "%;background:#ff94a7;-webkit-animation:love " + r_time + "s ease;-moz-animation:love " + r_time + "s ease;-ms-animation:love " + r_time + "s ease;animation:love " + r_time + "s ease'></div>");
$('.bg_heart').append("<div class='heart' style='width:" + (r_size - 10) + "px;height:" + (r_size - 10) + "px;left:" + (r_left + r_num) + "%;background:#ff94a7;-webkit-animation:love " + (r_time + 5) + "s ease;-moz-animation:love " + (r_time + 5) + "s ease;-ms-animation:love " + (r_time + 5) + "s ease;animation:love " + (r_time + 5) + "s ease'></div>");
$('.heart').each(function() {
var top = $(this).css("top").replace(/[^-\d\.]/g, '');
var width = $(this).css("width").replace(/[^-\d\.]/g, '');
if (top <= -100 || width >= 150) {
$(this).detach();
}
});
}, 500);
html,body{
height:100%
}
.bg_heart {
position: relative;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden
}
.heart {
position: absolute;
top: -50%;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-m-transform: rotate(-45deg);
transform: rotate(-45deg)
}
.heart:before {
position: absolute;
top: -50%;
left: 0;
display: block;
content: "";
width: 100%;
height: 100%;
background: inherit;
border-radius: 100%;
}
.heart:after {
position: absolute;
top: 0;
right: -50%;
display: block;
content: "";
width: 100%;
height: 100%;
background: inherit;
border-radius: 100%;
}
#-webkit-keyframes love {
0%{top:110%}
}
#-moz-keyframes love {
0%{top:110%}
}
#-ms-keyframes love {
0%{top:110%}
}
#keyframes love {
0%{top:110%}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header-plugin"></div>
<div class="bg_heart"></div>

To fly more chaotically use setInterval. You can also change the speed to whatever you need.
var brd = document.createElement("DIV");
document.body.insertBefore(brd, document.getElementById("board"));
const duration = 3000;
const speed = 0.5;
const cursorXOffset = 0;
const cursorYOffset = -5;
var hearts = [];
function generateHeart(x, y, xBound, xStart, scale)
{
var heart = document.createElement("DIV");
heart.setAttribute('class', 'heart');
brd.appendChild(heart);
heart.time = duration;
heart.x = x;
heart.y = y;
heart.bound = xBound;
heart.direction = xStart;
heart.style.left = heart.x + "px";
heart.style.top = heart.y + "px";
heart.scale = scale;
heart.style.transform = "scale(" + scale + "," + scale + ")";
if(hearts == null)
hearts = [];
hearts.push(heart);
return heart;
}
var down = false;
var event = null;
document.onmousedown = function(e) {
down = true;
event = e;
}
document.onmouseup = function(e) {
down = false;
}
document.onmousemove = function(e) {
event = e;
}
document.ontouchstart = function(e) {
down = true;
event = e.touches[0];
}
document.ontouchend = function(e) {
down = false;
}
document.ontouchmove = function(e) {
event = e.touches[0];
}
var before = Date.now();
var id = setInterval(frame, 5);
var gr = setInterval(check, 100);
function frame()
{
var current = Date.now();
var deltaTime = current - before;
before = current;
for(i in hearts)
{
var heart = hearts[i];
heart.time -= deltaTime;
if(heart.time > 0)
{
heart.y -= speed;
heart.style.top = heart.y + "px";
heart.style.left = heart.x + heart.direction * heart.bound * Math.sin(heart.y * heart.scale / 30) / heart.y * 100 + "px";
}
else
{
heart.parentNode.removeChild(heart);
hearts.splice(i, 1);
}
}
}
function check()
{
if(down)
{
var start = 1 - Math.round(Math.random()) * 2;
var scale = Math.random() * Math.random() * 0.8 + 0.2;
var bound = 30 + Math.random() * 20;
generateHeart(event.pageX - brd.offsetLeft + cursorXOffset, event.pageY - brd.offsetTop + cursorYOffset, bound, start, scale);
}
}
html,body{
height:100%
}
#keyframes heartfade {
0% {
opacity : 1;
}
50% {
opacity : 0;
}
}
.heart {
z-index : 999;
animation : heartfade 6s linear;
position : absolute;
}
.heart:before,
.heart:after {
content : "";
background-color : #ff94a7;
position : absolute;
height : 30px;
width : 45px;
border-radius : 15px 0px 0px 15px;
}
.heart:before {
transform : rotate(45deg);
}
.heart:after {
left : 10.5px;
transform : rotate(135deg);
}

Related

Animation optimization in pure js

There is an animation of the flight of leaves in pure js. The problem is that it needs to be optimized for maximum performance, because there will be more animations of this kind on the page. Besides optimizing the original SVG image and reducing the number of leaflets, what tips can you give to improve the performance of your code?
var LeafScene = function(el) {
this.viewport = el;
this.world = document.createElement('div');
this.leaves = [];
this.options = {
numLeaves: 6,
wind: {
magnitude: 0,
maxSpeed: 12,
duration: 300,
start: 0,
speed: 10
},
};
this.width = this.viewport.offsetWidth;
this.height = this.viewport.offsetHeight;
this.timer = 0;
this._resetLeaf = function(leaf) {
leaf.x = this.width * 2 - Math.random()*this.width*1.75;
leaf.y = -10;
leaf.z = Math.random()*200;
if (leaf.x > this.width) {
leaf.x = this.width + 10;
leaf.y = Math.random()*this.height/2;
}
if (this.timer == 0) {
leaf.y = Math.random()*this.height;
}
leaf.rotation.speed = Math.random()*10;
var randomAxis = Math.random();
if (randomAxis > 0.5) {
leaf.rotation.axis = 'X';
} else if (randomAxis > 0.25) {
leaf.rotation.axis = 'Y';
leaf.rotation.x = Math.random()*180 + 90;
} else {
leaf.rotation.axis = 'Z';
leaf.rotation.x = Math.random()*360 - 180;
leaf.rotation.speed = Math.random()*3;
}
leaf.xSpeedVariation = Math.random() * 0.8 - 0.4;
leaf.ySpeed = Math.random() + 1.5;
return leaf;
}
this._updateLeaf = function(leaf) {
var leafWindSpeed = this.options.wind.speed(this.timer - this.options.wind.start, leaf.y);
var xSpeed = leafWindSpeed + leaf.xSpeedVariation;
leaf.x -= xSpeed;
leaf.y += leaf.ySpeed;
leaf.rotation.value += leaf.rotation.speed;
var t = 'translateX( ' + leaf.x + 'px ) translateY( ' + leaf.y + 'px ) translateZ( ' + leaf.z + 'px ) rotate' + leaf.rotation.axis + '( ' + leaf.rotation.value + 'deg )';
if (leaf.rotation.axis !== 'X') {
t += ' rotateX(' + leaf.rotation.x + 'deg)';
}
leaf.el.style.webkitTransform = t;
leaf.el.style.MozTransform = t;
leaf.el.style.oTransform = t;
leaf.el.style.transform = t;
if (leaf.x < -10 || leaf.y > this.height + 10) {
this._resetLeaf(leaf);
}
}
this._updateWind = function() {
if (this.timer === 0 || this.timer > (this.options.wind.start + this.options.wind.duration)) {
this.options.wind.magnitude = Math.random() * this.options.wind.maxSpeed;
this.options.wind.duration = this.options.wind.magnitude * 50 + (Math.random() * 20 - 10);
this.options.wind.start = this.timer;
var screenHeight = this.height;
this.options.wind.speed = function(t, y) {
var a = this.magnitude/2 * (screenHeight - 2*y/3)/screenHeight;
return a * Math.sin(2*Math.PI/this.duration * t + (3 * Math.PI/2)) + a;
}
}
}
}
LeafScene.prototype.init = function() {
for (var i = 0; i < this.options.numLeaves; i++) {
var leaf = {
el: document.createElement('div'),
x: 0,
y: 0,
z: 0,
rotation: {
axis: 'X',
value: 0,
speed: 0,
x: 0
},
xSpeedVariation: 0,
ySpeed: 0,
path: {
type: 1,
start: 0,
},
image: 1
};
this._resetLeaf(leaf);
this.leaves.push(leaf);
this.world.appendChild(leaf.el);
}
this.world.className = 'leaf-scene';
this.viewport.appendChild(this.world);
this.world.style.webkitPerspective = "400px";
this.world.style.MozPerspective = "400px";
this.world.style.oPerspective = "400px";
this.world.style.perspective = "400px";
var self = this;
window.onresize = function(event) {
self.width = self.viewport.offsetWidth;
self.height = self.viewport.offsetHeight;
};
}
LeafScene.prototype.render = function() {
this._updateWind();
for (var i = 0; i < this.leaves.length; i++) {
this._updateLeaf(this.leaves[i]);
}
this.timer++;
requestAnimationFrame(this.render.bind(this));
}
var leafContainer = document.querySelector('.falling-leaves'),
leaves = new LeafScene(leafContainer);
leaves.init();
leaves.render();
body, html {
height: 100%;
}
.falling-leaves {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 100%;
max-width: 880px;
max-height: 880px;
transform: translate(-50%, 0);
border: 20px solid #fff;
border-radius: 50px;
background-size: cover;
overflow: hidden;
}
.leaf-scene {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 100%;
transform-style: preserve-3d;
}
.leaf-scene div {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background: url(https://www.flaticon.com/svg/static/icons/svg/892/892881.svg) no-repeat;
background-size: 100%;
transform-style: preserve-3d;
-webkit-backface-visibility: visible;
backface-visibility: visible;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<div class="falling-leaves"></div>
Unless you're using HTML Canvas, vanilla JS solutions are pretty heavy compared to CSS/JS hybrid because of the browser call stack.
It looks like this:
JS > Style > Layout > Paint > Composite
By minimizing the amount of calculations the browser has to do in JS and grouping reads/writes to the DOM you'll see a significant performance increase. The workload can be recorded with Chrome Dev tools under 'Performance' tab. And you'll be able to see every step the browser is taking to display the content. The less steps, the better performance .. simple as that.
You're writing to the DOM every single transform which is heavy even with 3d acceleration.
I usually make use of CSS variables and transitions for dynamic animation that I update in steps.
What you did is great otherwise. Try rendering on a HTML Canvas and your performance problems will vanish. Here's a start:
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API
But if you want or cant do canvas adapt to utilize CSS to not drop further than the Paint browser call for majority of frames.

Need help to limit how many tiles and target spawn in this game

I got some simple bomberman game from code pen.For my study,i need to limit how many tiles and target.For tiles max 32 and target 7 (tiles grey & target red).
Here the source : codepen.io/Digiben/pen/oGYGrx
I dont understand how the script create the target and tiles with random algoritm.
Thanks for anyone who look this thread.
window.onload = function(){
//Map Kelas
class Map {
constructor (nbX, nbY, tileSize){
this.nbX = nbX;
this.nbY = nbY;
this.mapArray = new Array(this.nbX);
this.tileSize = tileSize;
this.map = document.getElementById('map');
}
init() {
console.log('Map size: ' + this.nbX * this.nbY);
let i = 0;
let j = 0;
let bool = null;
this.map.style.width = (this.tileSize * this.nbX) + 'px';
this.map.style.height = this.tileSize * this.nbY + 'px';
for (i = 0; i < this.nbX; i++) {
this.mapArray[i] = new Array(this.nbY);
for (j = 0; j < this.nbY; j++) {
bool = Math.random() >= 0.7 ? true : false;
if (bool) {
for (var z = Things.length - 1; i >= 0; i-) {
Things[i]
}
} else if (!bool) {
this.mapArray[i][j] = 1;
}
}
}
}
appendTile(i, j) {
let tile = document.createElement('div');
this.map.appendChild(tile);
tile.style.width = this.tileSize + 'px';
tile.style.height = this.tileSize + 'px';
tile.classList.add('tile');
tile.style.left = (i * this.tileSize) + 'px';
tile.style.top = (j * this.tileSize) + 'px';
}
getMapArray () {
return this.mapArray;
}
getMapSize () {
return {sizeX: this.nbX, sizeY:this.nbY}
}
}
//Create Target
class Target {
constructor (map, tileSize) {
this.mapArray = map.getMapArray();
this.playerSpace = map.getMapSize();
this.targetsArray = new Array();
this.possiblePositionToStartX = new Array();
this.possiblePositionToStartY = new Array();
this.tileSize = tileSize;
this.map = document.getElementById('map');
this.totalTargets = 0;
}
getTotalTargets(){
return this.totalTargets;
}
//Show Total Target
showTotalTargets () {
let totalDiv = document.querySelector('#score strong');
totalDiv.innerHTML = ' / ' + this.totalTargets;
}
showTargets(i, j) {
let tile = document.createElement('div');
this.map.appendChild(tile);
tile.classList.add('target');
tile.style.width = this.tileSize + 'px';
tile.style.height = this.tileSize + 'px';
// set attribute to identify the target when we need to remove it
tile.setAttribute('data-pos', i + ':' + j );
// positionning and styling
tile.style.left = (i * this.tileSize) + 'px';
tile.style.top = (j * this.tileSize) + 'px';
tile.style.backgroundColor = 'red';
tile.style.opacity = 0.5;
}
createTargets() {
//Target looping
for (var i = 1; i < this.playerSpace.sizeX-1; i++) {
//Maks Target 2D 10x10
this.targetsArray[i] = new Array();
if (i == 1) this.targetsArray[i-1] = new Array();
if (i == 8) this.targetsArray[i+1] = new Array();
for (var j = 1; j < this.playerSpace.sizeY-1; j++) {
this.targetsArray[i][j] = 1;
//Target aLgorithm
//Player dont Looping On red Zone
this.possiblePositionToStartX.push(i+1);
this.possiblePositionToStartY.push(j+1);
//Target Array if 0 to display Win on the End
this.targetsArray[i][j] = 0;
//Total Targets
this.totalTargets++;
//Show Target On map
this.showTargets(i, j);
}
}
}
//Show Total Targets
this.showTotalTargets();
}
// Start Player
getPossiblePosToStart() {
//Random Start PLayer
let xPos = this.possiblePositionToStartX[Math.floor(Math.random() * (this.possiblePositionToStartX.length))];
let yPos = this.possiblePositionToStartY[Math.floor(Math.random() * (this.possiblePositionToStartY.length))];
return {x: xPos, y: yPos}
}
//Player Array
getTargetsArray(){
return this.targetsArray;
}
}
//PLayer CLass
class Player {
constructor (mapArray, map, targets, tileSize) {
this.positionArray = mapArray;
this.position = {x: 0, y: 0}
this.playerDiv = document.getElementById('player');
this.playerDiv.style.left = 0;
this.playerDiv.style.top = 0;
this.playerDiv.style.right = 0;
this.playerDiv.style.bottom = 0;
this.playerDiv.style.width = tileSize + 'px';
this.playerDiv.style.height = tileSize + 'px';
this.playerSpace = map.getMapSize();
this.playerMap = map.getMapArray();
this.score = 0;
this.targetsArray = targets.getTargetsArray();
this.totalTargets = targets.getTotalTargets();
this.tileSize = tileSize;
}
//Record Posisition Player
recordPosition(mapArray){
this.positionArray = mapArray;
}
//Reset Score when Restart The game
static resetScore() {
let scoreSpan = document.querySelector('#score span'); scoreSpan.innerHTML = '0';
}
//Set Palyer
setPosition (position){
this.playerDiv.style.left = (position.x * this.tileSize) + 'px';
this.playerDiv.style.top = (position.y * this.tileSize) + 'px';
this.position.x = position.x;
this.position.y = position.y;
}
getPosition() {
return this.position;
}
//Limt Map
moveRight() {
if(this.position.x > this.playerSpace.sizeX-2) return false;
if(this.positionArray[this.position.x+1][this.position.y] != 0){
this.position.x++;
let nb = this.playerDiv.style.left.split('px');
this.playerDiv.style.left = (parseInt(nb[0]) + this.tileSize) + 'px';
console.log('Droite | X : ' + this.playerDiv.style.left);
console.log(this.position.x + ' : ' + this.position.y);
} else {
console.log('Not OK');
}
}
moveDown() {
if(this.position.y > this.playerSpace.sizeY-2) return false;
if(this.positionArray[this.position.x][this.position.y+1] != 0){
this.position.y++;
let nb = this.playerDiv.style.top.split('px');
this.playerDiv.style.top = (parseInt(nb[0]) + this.tileSize) + 'px';
console.log('Bas | Y : ' + this.playerDiv.style.top);
console.log(this.position.x + ' : ' + this.position.y);
} else {
console.log('Not OK');
}
}
moveLeft() {
if(this.position.x == 0) return false;
if(this.positionArray[this.position.x-1][this.position.y] != 0){
this.position.x--;
let nb = this.playerDiv.style.left.split('px');
this.playerDiv.style.left = (parseInt(nb[0]) - this.tileSize) + 'px';
console.log('Gauche | X : ' + this.playerDiv.style.left);
console.log(this.position.x + ' : ' + this.position.y);
} else {
console.log('Not OK');
}
}
moveUp() {
if(this.position.y <= 0) return false;
if(this.positionArray[this.position.x][this.position.y-1] != 0){
this.position.y--;
let nb = this.playerDiv.style.top.split('px');
this.playerDiv.style.top = (parseInt(nb[0]) - this.tileSize) + 'px';
console.log('Haut | Y : ' + this.playerDiv.style.top);
console.log(this.position.x + ' : ' + this.position.y);
} else {
console.log('Not OK');
}
}
//Update Score
updateScore () {
let scoreDiv = document.querySelector('#score span');
scoreDiv.innerHTML = this.score;
//Winner Message
if(this.score == this.totalTargets) document.querySelector ('#win').classList.add('show');
console.log('Score : ' + this.score);
}
//Update Target Array
updateTargetsArray (posx, posy){
this.targetsArray[posx][posy] = 1;
console.log('Array state : ');
console.log(this.targetsArray);
}
//Remove Target
removeTarget(posx, posy) {
let targetToRemove = document.querySelectorAll('.target');
let coords = posx + ':' + posy;
let attr = '';
//Loop To find Right Target accroding Coordinates Player
for (var i = 0; i< targetToRemove.length; i++) {
attr = targetToRemove[i].getAttribute('data-pos');
if(attr == coords) {
targetToRemove[i].remove();
//Update Score
this.score++;
this.updateScore();
}
}
//Remove Html node (Remove Array Target)
if(this.targetsArray[posx][posy] == 0){
this.targetsArray[posx][posy] == 1;
}
}
//Plant Bomb
plantBomb(){
//Make Child Bomb
let map = document.getElementById('map');
let bomb = document.createElement('div');
map.appendChild(bomb);
bomb.style.width = this.tileSize + 'px';
bomb.style.height = this.tileSize + 'px';
//Posision Bomb
bomb.classList.add('bomb');
bomb.style.left = (this.position.x * this.tileSize) + 'px';
bomb.style.top = (this.position.y * this.tileSize) + 'px';
//Variables
var posx = this.position.x;
var posy = this.position.y;
var that = this;
var timer = setInterval(bombTimer, 500, posx, posy, that);
var iter = 0;
//BombTimer
function bombTimer() {
switch (iter) {
case 1:
bomb.classList.add('waiting');
break;
case 2:
bomb.classList.add('before');
bomb.classList.remove('waiting');
break;
case 3:
bomb.classList.add('explode');
bomb.classList.remove('before');
break;
case 4:
clearInterval(timer);
bomb.remove();
that.updateTargetsArray(posx, posy);
that.removeTarget(posx, posy);
default:
break;
}
iter++;
}
}
}
//Game Class
class Game {
constructor (tileSize, mapX, mapY) {
//Create Map
var map = new Map(mapX,mapY, tileSize);
map.init();
//Create Target
var targets = new Target(map, tileSize);
targets.createTargets();
//Create PLayer
var player = new Player(map.getMapArray(), map, targets, tileSize);
//Place The player
player.setPosition(targets.getPossiblePosToStart());
//Keyboard Events
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
player.moveUp();
}
else if (e.keyCode == '40') {
player.moveDown();
}
else if (e.keyCode == '37') {
player.moveLeft();
}
else if (e.keyCode == '39') {
player.moveRight();
}
else if (e.keyCode == '32') {
player.plantBomb();
}
}
}
//Destroy Game
static destroy () {
let targets = document.querySelectorAll('.target');
let tiles = document.querySelectorAll('.tile');
Player.resetScore();
if(tiles){
targets.forEach(function(element) {
element.remove();
});
tiles.forEach(function(element) {
element.remove();
});
}
}
}
class Session {
constructor () {
this.totalTargets = 0;
this.players = {};
this.restartBtn = document.querySelector('#restart');
this.restartBtn.addEventListener('click', function() {
Session.restart();
});
}
static restart () {
Game.destroy();
var game = new Game(25, 10, 10);
}
}
var session = new Session();
};
#map {
width: 500px;
height: 500px;
background: lightgrey;
position: relative;
margin: auto;
}
#game {
width: 500px;
height: 500px;
position: relative;
margin: auto;
}
#map .tile {
width: 50px;
height: 50px;
background: grey;
position: absolute;
outline: 1px solid #eee;
}
#map .target {
width: 50px;
height: 50px;
background: red;
position: absolute;
outline: 1px solid #eee;
}
#map #player {
border-radius: 25%;
width: 50px;
height: 50px;
position: absolute;
background: #222222;
z-index: 1;
transition: 0.1s;
}
.bomb {
border-radius: 100%;
width: 50px;
height: 50px;
position: absolute;
background: #333;
z-index: 1;
transition: 0.3s ease;
}
.bomb.waiting {
animation: waiting 2s infinite;
}
.bomb.before {
animation: before 1s infinite;
}
.bomb.explode {
animation: explode 1s infinite;
}
#score p, #score span {
font-family: sans-serif;
color: #333;
font-size: 16px;
display: inline;
}
#keyframes waiting {
0% {
transform: scale(0.9);
}
100% {
transform: scale(1.1);
}
}
#keyframes before {
0% {
transform: scale(1.0);
background: orange;
}
100% {
transform: scale(1.2);
background: red;
}
}
#keyframes explode {
0% {
transform: scale(1.0);
background: red;
opacity: 1;
}
100% {
transform: scale(2);
background: yellow;
opacity: 0;
}
}
#keyframes win {
0% {
opacity: 0;
}
10% {
opacity: 1;
}
66% {
opacity: 1;
}
100% {
opacity: 0;
}
}
h4 {
font-family: sans-serif;
color: #333;
text-align: center;
}
p, strong {
font-family: sans-serif;
color: #333;
text-align: left;
font-size: 12px;
}
#win {
position: fixed;
left: 0;
right: 0;
top:0;
bottom: 0;
z-index: 9999999;
background: rgba(181, 181, 195, 0.1);
pointer-events: none;
opacity: 0;
}
#win p {
color: red;
font-size: 130px;
text-align: center;
font-family: sans-serif;
text-transform: uppercase;
height: 100%;
margin: 0;
top: 50%;
position: absolute;
left: 50%;
transform: translate(-50%, -25%);
right: 0;
bottom: 0;
font-weight: bold;
text-shadow: 5px 5px #333;
}
#win.show {
animation: win 4s ease;
}
#restart {
text-align: center;
padding: 10px 20px;
font-family: sans-serif;
color: #333;
outline: #ccc 1px solid;
display: table;
margin: auto;
margin-top: 20px;
cursor: pointer;
transition: 0.1s ease;
}
#restart:hover {
background: #eee;
}
<!DOCTYPE html>
<html>
<head>
<title>Bomberman</title>
<link href="bomber.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="1.js"></script>
</head>
<body>
<h4>Space bar to plant a bomb / Arrows to move </h4>
<div id="win"><p>WIN !</p></div>
<div id="restart"> RESTART </div>
<div id="score"><p>Score: </p><span>0</span><strong> / 0</strong></div>
<section id="game">
<div id="map">
<div id="player"></div>
</div>
</section>
</body>
</html>
I'm not certain I understand your question, but I think you're trying to debug the createTargets method in the Targets class. The problem there is an extra closing bracket (}) right before the line with //Show Total Targets.

Javascript - moving multiple images inside a div, with border control

Little premise: I didn't want to make this question, because I thought it was a too personal and generic problem; but after 2 days without any improvement, I couldn't resist anymore.
So basically, my project is an aquarium with multiple fishes inside.
It all works fine, the only problem is that, in short words: the first fish image remains inside the div(it even stops too soon), the second one arrives a bit farther, the third even farther, and so on.
The opposite thing happens with the top margin: going forward, the last fish is always farther from the margin, and I can't find out the reason.
My scope is to keep all the fishes inside the "acquario" div (which has the black borders).
P.S. With sx and dx margins, they have no problem.
var BORDER_LEFT_RIGHT = 7;
var BORDER_TOP_DOWN = 28;
var fishes = new Array();
var nextId = 0;
var heightMax;
var widthMax;
var n; //initial direction, see createFish()
init();
/* light blue fish (dory, to clarify)*/
createFish("https://s18.postimg.org/n8sqmtjkp/pesce1_sx.png", "https://s30.postimg.org/6w8xyqwep/pesce1_dx.png");
/* white and yellow fish */
createFish("https://s28.postimg.org/6aalv0pst/pesce2_sx.png", "https://s29.postimg.org/dxbi0vypz/pesce2_dx.png");
/* dark blue fish */
createFish("https://s24.postimg.org/sbgt8zn6t/pesce3_sx.png", "https://s29.postimg.org/v65opob7r/pesce3_dx.png");
/* white-blue-yellow fish */
createFish("https://s30.postimg.org/62lb9bfwx/pesce4_sx.png", "https://s28.postimg.org/kt5m4ea65/pesce4_dx.png");
/* orange fish */
createFish("https://s18.postimg.org/q5sq0saex/pesce5_sx.png", "https://s18.postimg.org/uqnwe2vex/pesce5_dx.png");
showFishes();
function init() {
heightMax = document.getElementById("acquario").clientHeight - BORDER_TOP_DOWN;
widthMax = document.getElementById("acquario").clientWidth - BORDER_LEFT_RIGHT;
n = 1;
}
function createFish(src1, src2) {
imgFishSX = new Image();
imgFishDX = new Image();
imgFishSX.src = src1;
imgFishDX.src = src2;
n *= -1;
var fish = {
id: nextId,
/* default x position: random number between 1 and widthMax */
x: Math.floor((Math.random() * widthMax - imgFishSX.width) + 1),
/* default y position: random number between 1 and heightMax */
y: Math.floor((Math.random() * heightMax - imgFishSX.height) + 1),
xIncrease: n * getIncrease(),
yIncrease: n * getIncrease(),
imageSX: imgFishSX,
imageDX: imgFishDX
};
addFishToArray((fish));
nextId++;
}
function addFishToArray(fish) {
fishes.push(fish);
}
function showFishes() {
var node = document.getElementById("acquario");
var stringToInner = "";
var src;
/* first, we make the string with all the img filled in */
for (var i = 0; i < fishes.length; i++) {
/* we have to check if the default increase direction was <-- or --> */
fishes[i].xIncrease > 0 ? src = fishes[i].imageSX.src : src = fishes[i].imageDX.src;
/* z-index --> overlap priority */
stringToInner += "<img src =\"" + src +
"\" id=\"" + fishes[i].id + "\" style= \"margin-left: " +
fishes[i].x + "px;margin-top: " + fishes[i].y + "px;z-index: " +
fishes[i].id + ";position: absolute;\">";
stringToInner += "<br>";
}
/* then, we insert it */
node.innerHTML = stringToInner;
/* let's raise hell! */
moveFishes();
}
function getIncrease() {
return Math.floor((Math.random() * 5) + 1);
}
function moveFishes() {
/* scroll the array: we need to check each fish one by one */
for (var i = 0; i < fishes.length; i++) {
moveFish(fishes[i]);
}
/* infinite loop */
setTimeout(function() {
moveFishes()
}, 50);
}
function moveFish(fish) {
/* with this node, I'll apply changes to my html document */
node = document.getElementById(fish.id);
/* we are inside, just move */
if (fish.x > 0 && fish.x < widthMax - node.width && fish.y > 0 && fish.y < heightMax - node.height) {
node.style.marginLeft = fish.x + "px";
node.style.marginTop = fish.y + "px";
fish.x += fish.xIncrease;
fish.y += fish.yIncrease;
/* too --> , we need to get <-- */
} else if (fish.x >= widthMax - node.width) {
node.src = fish.imageDX.src;
fish.xIncrease = -getIncrease();
fish.x += fish.xIncrease;
/* too <-- , we need to get --> */
} else if (fish.x <= 0) {
node.src = fish.imageSX.src;
fish.xIncrease = 5;
fish.x += getIncrease();
/* too up, we need to get down */
} else if (fish.y >= heightMax - node.height) {
fish.yIncrease = -getIncrease();
fish.y += fish.yIncrease;
/* too down, we need to get up */
} else if (fish.y <= 0) {
fish.yIncrease = getIncrease();
fish.y += fish.yIncrease;
}
}
* {
box-sizing: border-box;
}
.row::after {
content: "";
clear: both;
display: block;
}
html {
background: url("https://s24.postimg.org/rakxoa7sl/sfondo.jpg") no-repeat center center fixed;
-webkibact-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
html,
body {
height: 100%;
margin: 0;
}
#main {
margin: 0;
height: 100%;
}
#acquario {
border-bottom: 28px solid black;
border-top: 28px solid black;
border-right: 7px solid black;
border-left: 7px solid black;
height: 100%;
}
<body>
<div id="main">
<div id="acquario">
</div>
</div>
</body>
do you want the fishes to bound off the walls or to hide under the wall? and why do you use margin-left and margin-top instead of top and left properties? it makes the aquarium scrolling. Is it ok now?
var BORDER_LEFT_RIGHT = 7;
var BORDER_TOP_DOWN = 28;
var fishes = new Array();
var nextId = 0;
var heightMax;
var widthMax;
var n; //initial direction, see createFish()
init();
/* light blue fish (dory, to clarify)*/
createFish("https://s18.postimg.org/n8sqmtjkp/pesce1_sx.png", "https://s30.postimg.org/6w8xyqwep/pesce1_dx.png");
/* white and yellow fish */
createFish("https://s28.postimg.org/6aalv0pst/pesce2_sx.png", "https://s29.postimg.org/dxbi0vypz/pesce2_dx.png");
/* dark blue fish */
createFish("https://s24.postimg.org/sbgt8zn6t/pesce3_sx.png", "https://s29.postimg.org/v65opob7r/pesce3_dx.png");
/* white-blue-yellow fish */
createFish("https://s30.postimg.org/62lb9bfwx/pesce4_sx.png", "https://s28.postimg.org/kt5m4ea65/pesce4_dx.png");
/* orange fish */
createFish("https://s18.postimg.org/q5sq0saex/pesce5_sx.png", "https://s18.postimg.org/uqnwe2vex/pesce5_dx.png");
showFishes();
function init() {
heightMax = document.getElementById("acquario").clientHeight + BORDER_TOP_DOWN;
widthMax = document.getElementById("acquario").clientWidth + BORDER_LEFT_RIGHT;
n = 1;
}
function createFish(src1, src2) {
imgFishSX = new Image();
imgFishDX = new Image();
imgFishSX.src = src1;
imgFishDX.src = src2;
n *= -1;
var fish = {
id: nextId,
/* default x position: random number between 1 and widthMax */
x: Math.floor((Math.random() * (widthMax - BORDER_LEFT_RIGHT - imgFishSX.width)) + BORDER_LEFT_RIGHT),
/* default y position: random number between 1 and heightMax */
y: Math.floor((Math.random() * (heightMax - BORDER_TOP_DOWN - imgFishSX.height)) + BORDER_TOP_DOWN),
xIncrease: n * getIncrease(),
yIncrease: n * getIncrease(),
imageSX: imgFishSX,
imageDX: imgFishDX
};
addFishToArray((fish));
nextId++;
}
function addFishToArray(fish) {
fishes.push(fish);
}
function showFishes() {
var node = document.getElementById("acquario");
var stringToInner = "";
var src;
/* first, we make the string with all the img filled in */
for (var i = 0; i < fishes.length; i++) {
/* we have to check if the default increase direction was <-- or --> */
fishes[i].xIncrease > 0 ? src = fishes[i].imageSX.src : src = fishes[i].imageDX.src;
/* z-index --> overlap priority */
stringToInner += "<img src =\"" + src +
"\" id=\"" + fishes[i].id + "\" style= \"left: " +
fishes[i].x + "px;top: " + fishes[i].y + "px;z-index: " +
fishes[i].id + ";position: absolute;\">";
stringToInner += "<br>";
}
/* then, we insert it */
node.innerHTML = stringToInner;
/* let's raise hell! */
moveFishes();
}
function getIncrease() {
return Math.floor((Math.random() * 5) + 1);
}
function moveFishes() {
/* scroll the array: we need to check each fish one by one */
for (var i = 0; i < fishes.length; i++) {
moveFish(fishes[i]);
}
/* infinite loop */
setTimeout(function() {
moveFishes()
}, 50);
}
function moveFish(fish) {
/* with this node, I'll apply changes to my html document */
node = document.getElementById(fish.id);
/* we are inside, just move */
if (fish.x > BORDER_LEFT_RIGHT && fish.x < widthMax - node.width && fish.y > BORDER_TOP_DOWN && fish.y < heightMax - node.height) {
node.style.left = fish.x + "px";
node.style.top = fish.y + "px";
fish.x += fish.xIncrease;
fish.y += fish.yIncrease;
/* too --> , we need to get <-- */
} else if (fish.x >= widthMax - node.width) {
node.src = fish.imageDX.src;
fish.xIncrease = -getIncrease();
fish.x += fish.xIncrease;
/* too <-- , we need to get --> */
} else if (fish.x <= BORDER_LEFT_RIGHT) {
node.src = fish.imageSX.src;
fish.xIncrease = 5;
fish.x += getIncrease();
/* too up, we need to get down */
} else if (fish.y >= heightMax - node.height) {
fish.yIncrease = -getIncrease();
fish.y += fish.yIncrease;
/* too down, we need to get up */
} else if (fish.y <= BORDER_TOP_DOWN) {
fish.yIncrease = getIncrease();
fish.y += fish.yIncrease;
}
}
* {
box-sizing: border-box;
}
.row::after {
content: "";
clear: both;
display: block;
}
html {
background: url("https://s24.postimg.org/rakxoa7sl/sfondo.jpg") no-repeat center center fixed;
-webkibact-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
html,
body {
height: 100%;
margin: 0;
}
#main {
margin: 0;
height: 100%;
}
#acquario {
border-bottom: 28px solid black;
border-top: 28px solid black;
border-right: 7px solid black;
border-left: 7px solid black;
height: 100%;
}
<body>
<div id="main">
<div id="acquario">
</div>
</div>
</body>
I know Pawel has fixed your issue, but I did state I would provide a canvas version so here it is
jsFiddle : https://jsfiddle.net/CanvasCode/zh0b7zrj/1/
HTML :
<canvas id="myCanvas"></canvas>
CSS :
html,
body {
width: 100%;
height: 100%;
margin: 0px;
overflow: hidden;
}
Javascript :
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");
var backgroundImage = new Image();
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = document.body.clientHeight; //document.height is obsolete
// Fish
function FishObject(xSet, ySet, xSpeed, ySpeed, spriteUrlRight, spriteUrlLeft) {
this.XPos = xSet;
this.YPos = ySet;
this.XDefaultSpeed = xSpeed;
this.YDefaultSpeed = ySpeed;
this.xSpeed = this.XDefaultSpeed;
this.ySpeed = this.YDefaultSpeed;
this.RightSprite = new Image();
this.RightSprite.src = spriteUrlRight;
this.LeftSprite = new Image();
this.LeftSprite.src = spriteUrlLeft;
}
FishObject.prototype.Draw = function(ctx) {
if (this.xSpeed > 0) {
ctx.drawImage(this.RightSprite, this.XPos, this.YPos);
} else {
ctx.drawImage(this.LeftSprite, this.XPos, this.YPos);
}
}
FishObject.prototype.Update = function(ctx) {
this.XPos += this.xSpeed;
this.YPos += this.ySpeed;
if (this.XPos <= 0) {
this.xSpeed = this.XDefaultSpeed;
} else if ((this.XPos + this.RightSprite.width) >= canvas.width) {
this.xSpeed = -this.XDefaultSpeed;
}
if (this.YPos <= 0) {
this.ySpeed = this.YDefaultSpeed;
} else if ((this.YPos + this.RightSprite.height) >= canvas.height) {
this.ySpeed = -this.YDefaultSpeed;
}
}
backgroundImage.src = 'https://s24.postimg.org/rakxoa7sl/sfondo.jpg';
var Fishs = [];
Fishs.push(new FishObject(0, 0, 1, 1, "https://s18.postimg.org/n8sqmtjkp/pesce1_sx.png",
"https://s30.postimg.org/6w8xyqwep/pesce1_dx.png"));
Fishs.push(new FishObject(0, 0, 2, 1.2, "https://s28.postimg.org/6aalv0pst/pesce2_sx.png",
"https://s29.postimg.org/dxbi0vypz/pesce2_dx.png"));
Fishs.push(new FishObject(0, 0, 1.7, 2.8, "https://s24.postimg.org/sbgt8zn6t/pesce3_sx.png",
"https://s29.postimg.org/v65opob7r/pesce3_dx.png"));
Fishs.push(new FishObject(0, 0, 0.2, 0.5, "https://s30.postimg.org/62lb9bfwx/pesce4_sx.png",
"https://s28.postimg.org/kt5m4ea65/pesce4_dx.png"));
Fishs.push(new FishObject(0, 0, 0.7, 0.1, "https://s18.postimg.org/q5sq0saex/pesce5_sx.png",
"https://s18.postimg.org/uqnwe2vex/pesce5_dx.png"));
setInterval(function() {
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(backgroundImage, 0, 0);
for (var i = 0; i < Fishs.length; i++) {
var fishObject = Fishs[i];
fishObject.Draw(ctx);
fishObject.Update(ctx);
}
}, (1000 / 60)); // 60 FPS (frames per second)

Javascript on scroll resize ID with a minimum value applied first

I have a element when if scrolled down I'm upscaling the element by a X value which works completely fine.
The issue is though the SCALE by default is 0 so as soon as it's applied it starts from 0 when I'd like it to be from 1.
I have then set a scroll max position of 200px and a max SCALE of 2.0 in the CSS with an important tag and that seems to work.
If anyone can assist with this issue your efforts will be super helpful.
function parallaxy()
{
offset2 = +(scrollVal * 0.009);
layer2.style.webkitTransform = "scale(" + offset2 + ")";
layer2.style.MozTransform = "scale(" + offset2 + ")";
layer2.style.msTransform = "scale(" + offset2 + ")";
layer2.style.OTransform = "scale(" + offset2 + ")";
layer2.style.transform = "scale(" + offset2 + ")";
}
var body = document.body;
var container = document.getElementById("parallax");
var isTouchscreen;
var scrollVal = 1;
var offset2;
var maxoffset = 10;
var layer2 = document.getElementById("layer-2");
function setup() {
/*var platform = navigator.platform.toLowerCase();
var userAgent = navigator.userAgent.toLowerCase();
if ( platform.indexOf('ipad') != -1 || platform.indexOf('iphone') != -1 )
{
isTouchscreen = 1;
container.setAttribute("class", "touch");
body.style.backgroundImage = 'none';
}
else if (platform.indexOf('win32') != -1 || platform.indexOf('linux') != -1)
{
isTouchscreen = 0;
if ($.browser.webkit)
{
$.srSmoothscroll();
}
}
else
{
isTouchscreen = 0;
}*/
}
function parallaxy() {
//var elem = document.getElementById("layer1");
//elem.style.transform = "10px";
//console.log(scrollVal);
offset2 = +(scrollVal * 0.01);
if (offset2 > maxoffset) {
offset2 = maxoffset;
} else {
offset2 = +(scrollVal * 0.01);
}
layer2.style.webkitTransform = "scale(" + offset2 + ")";
layer2.style.MozTransform = "scale(" + offset2 + ")";
layer2.style.msTransform = "scale(" + offset2 + ")";
layer2.style.OTransform = "scale(" + offset2 + ")";
layer2.style.transform = "scale(" + offset2 + ")";
//console.log(offset2);
}
function scrollHandler(e) {
scrollVal = Math.max(window.pageYOffset, 0)+100;
console.log(offset2);
/* UNCOMMENT THESE LINES TO ABORT PARALLAX STUFF */
/*
isTouchscreen = 1;
container.setAttribute("class", "touch");
body.style.backgroundImage = 'none';
*/
if (isTouchscreen != 1) {
parallaxy();
}
}
body.onload = setup();
document.addEventListener('scroll', scrollHandler, false);
#container .container {
z-index: 999;
position: relative;
}
#parallax {
position: relative;
z-index: 10;
top: 50px !important;
width: 100%;
height: 1080px;
overflow: hidden;
}
.parallax_layer {
width: 100%;
-webkit-transform: translate3d(0, 0, 0);
-moz-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
-o-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
#container.touch .parallax_layer {
position: absolute;
}
#layer-2 {
z-index: 999;
width: 100%;
height: 1080px;
position: absolute;
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
#layer-2 {
background: url("http://www.staples.co.uk/content/images/product/GenesisExtraLarge/45/56/asset.1714556.jpg") transparent center top no-repeat;
z-index: 1000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parallax">
<div class="parallax_layer" id="layer-2"></div>
</div>

Jquery word for word fade in effect

ive been looking in about for this exact script for a while and i cant get it to work. Im looking to use a fade in effect from left to right word by word.
For example
<div class="box5">
<h1>Lorem ipsum dolor sit amet, ne mel vero impetus voluptatibus
</h1>
</div>
I want this to fade in then enough line to fade in word by word slightly later using a delay.
My current fade in works but it does it by the full container it looks like this
.reveal {
position: relative;
overflow: hidden;
}
/*initial - hidden*/
.reveal .reveal__cover {
position: absolute;
top: 0;
left: -250px;
height: 100%;
margin: 2px;
width: calc(100% + 250px);
}
.reveal .reveal__cover.reveal__uncovered {
position: absolute;
top: 0;
left: 100%;
height: 100%;
width: calc(100% + 250px);
margin: 2px;
transition: left 2500ms ease-out 0ms;
}
.reveal__cover-section {
height: 100%;
float: right;
/* NOTE: Background must match existing background */
/*background: #000;*/
background: #fff;
width: 2%;
}
.reveal__10 {
opacity: 0.1;
}
.reveal__20 {
opacity: 0.2;
}
.reveal__30 {
opacity: 0.3;
}
.reveal__40 {
opacity: 0.4;
}
.reveal__50 {
opacity: 0.5;
}
.reveal__60 {
opacity: 0.6;
}
.reveal__70 {
opacity: 0.7;
}
.reveal__80 {
opacity: 0.8;
}
.reveal__90 {
opacity: 0.9;
}
.reveal__100 {
opacity: 1;
width: 82%;
}
Then JS
function replaceAllInstances(source, search, replacement) {
var regex = new RegExp(search, "g");
var result = source.replace(regex, replacement);
return result;
}
$.fn.isOnScreen = function (x, y) {
if (x == null || typeof x == 'undefined')
x = 1;
if (y == null || typeof y == 'undefined')
y = 1;
var win = $(window);
var viewport = {
top: win.scrollTop(),
left: win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var height = this.outerHeight();
var width = this.outerWidth();
if (!width || !height) {
return false;
}
var bounds = this.offset();
bounds.right = bounds.left + width;
bounds.bottom = bounds.top + height;
var visible = (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
if (!visible) {
return false;
}
var deltas = {
top: Math.min(1, (bounds.bottom - viewport.top) / height),
bottom: Math.min(1, (viewport.bottom - bounds.top) / height),
left: Math.min(1, (bounds.right - viewport.left) / width),
right: Math.min(1, (viewport.right - bounds.left) / width)
};
return (deltas.left * deltas.right) >= x && (deltas.top * deltas.bottom) >= y;
};
/*
* Init specified element so it can be gradually revealed.
*
* Limitations:
* Only works on backgrounds with a solid color.
*
* #param options = {
* id:'box3'
* ,background='#ffffff' //default
* ,delay='0' //default
* }
*
*/
$.fn.initReveal = function (options) {
console.log('-------------');
console.log('selector:' + this.selector);
var parent = $(this).parent();
//grab a copy of the contents, then remove it from DOM
var contents = $(this).clone();
$(this).empty();
var revealHtmlBlock = "<div class='reveal'> <div class='text reveal__inner reveal__inner-{class}'> </div> <div class='reveal__cover reveal__cover-{class}'> <div class='reveal__cover-section reveal__100'></div> <div class='reveal__cover-section reveal__90'></div> <div class='reveal__cover-section reveal__80'></div> <div class='reveal__cover-section reveal__70'></div> <div class='reveal__cover-section reveal__60'></div> <div class='reveal__cover-section reveal__50'></div> <div class='reveal__cover-section reveal__40'></div> <div class='reveal__cover-section reveal__30'></div> <div class='reveal__cover-section reveal__20'></div> <div class='reveal__cover-section reveal__10'></div> </div> </div>";
revealHtmlBlock = replaceAllInstances(revealHtmlBlock, "{class}", options.id);
$(revealHtmlBlock).appendTo(parent);
contents.appendTo($('.reveal__inner-' + options.id));
//handle options
//delay
if (options.delay === undefined) {
console.log('delay set to 0');
options.delay = 0; //set default
} else {
console.log('delay set to:' + options.delay);
}
var revealElementFunction = function (options) {
$(this).performReveal(options);
};
//background
if (options.background !== undefined) {
$('.reveal__cover-' + options.id + ' .reveal__cover-section').css({'background-color': options.background});
}
//trigger the reveal at the specified time, unless auto is present and set to false
if (options.auto === undefined || (options.auto !== undefined && options.auto)) {
setTimeout(function () {
console.log('call');
revealElementFunction(options);
}, options.delay);
}
//trigger on-visible
if (options.trigger !== undefined) {
var revealOnScreenIntervalIdMap = {};
function uncoverText() {
var onscreen = $('.reveal__inner-box4').isOnScreen();
if ($('.reveal__inner-' + options.id).isOnScreen()) {
$('.reveal__cover-' + options.id).addClass('reveal__uncovered');
revealOnScreenIntervalIdMap[options.id] = window.clearInterval(revealOnScreenIntervalIdMap[options.id]);
}
}
function showTextWhenVisible() {
revealOnScreenIntervalIdMap[options.id] = setInterval(uncoverText, 800);
}
showTextWhenVisible();
}
};
//--------------------
/*
* trigger options:
* immediately (on page load)
* on event, eg. onclick
* on becoming visible, after it scrolls into view, or is displayed after bein ghidden
*
* #param options = {
* id:'box3'
* }
*
*/
$.fn.performReveal = function (options) {
var _performReveal = function () {
$('.reveal__cover-' + options.id).addClass('reveal__uncovered');
};
//allow time for init code to complete
setTimeout(_performReveal, 250);
};
Main JS
jQuery(function () {
//Box 1: reveal immediately - on page load
//NOTE: id does refer to an element id, It is used to
// uniquely refer to the element to be revealed.
var options1 = {
id: 'box1',
background: '#008d35'
};
$('.box1').initReveal(options1);
//------------------------
//Box 2: reveal after specified delay
var options2 = {
id: 'box2'
, delay: 3000
, background: '#008d35'
};
$('.box2').initReveal(options2);
//------------------------
//Box 3: reveal on event - eg. onclick
var options3 = {
id: 'box3'
, auto: false
};
var box3 = $('.box3');
box3.initReveal(options3);
$('.btn-reveal').on('click', function () {
box3.performReveal(options3);
});
//------------------------
//Box 4: Reveal when element scrolls into the viewport
var options4 = {
id: 'box4'
, auto: false
, trigger: 'on-visible'
};
$('.box4').initReveal(options4);
});
//------------------------
//Box 5 reveal
var options5 = {
id: 'box5'
, delay: 2500 ,
background: '#008d35'
};
$('.box5').initReveal(options5);
does anyone have any idea how to make it work word by word and not line by line
Here's a simple approach that you can build on. It creates the needed spans and fades them in based on interval value you set.
var fadeInterval = 300
$('h1').html(function(_, txt){
var words= $.trim(txt).split(' ');
return '<span>' + words.join('</span> <span>') + '</span>';
}).find('span').each(function(idx, elem){
$(elem).delay(idx * fadeInterval).fadeIn();
});
DEMO

Categories