Javascript: Looping sound with buttons. Error with boolean - javascript

CSS
.btnMusic {
background-color: #4CAF50;
/* Green */
border: none;
color: white;
padding: 50px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
width: 130px;
height: 130px;
margin-bottom: 5px;
}
.btnMusic:hover {
background-color: darkgreen;
cursor: pointer;
border: 1px solid black;
}
#options {
margin-top: 20px;
}
JS
var boolean_loop = false;
var sound_highhat = new Audio("sound/sound_highhat.mp3");
var sound_lowhat = new Audio("sound/sound_lowhat.mp3");
var sound_synth = new Audio("sound/sound_synth.mp3");
var sound_beat = new Audio("sound/sound_beat.mp3");
function sound_loop() {
if (boolean_loop === false) {
document.getElementById("loopoption").innerHTML = "Loop (Active)";
boolean_loop = true;
} else if (boolean_loop === true) {
document.getElementById("loopoption").innerHTML = "Loop";
boolean_loop = false;
}
}
function audiostop() {
sound_highhat.pause()
sound_highhat.currentTime = 0.0;
sound_lowhat.pause()
sound_lowhat.currentTime = 0.0;
sound_synth.pause()
sound_synth.currentTime = 0.0;
sound_beat.pause()
sound_beat.currentTime = 0.0;
}
function play_highhat() {
if (boolean_loop === true) {
sound_highhat.addEventListener("ended", function() {
this.currentTime = 0;
this.play();
}, false);
sound_highhat.play();
} else if (boolean_loop === false) {
sound_highhat.play();
}
}
function play_lowhat() {
if (boolean_loop === true) {
sound_lowhat.addEventListener("ended", function() {
this.currentTime = 0;
this.play();
}, false);
sound_lowhat.play();
} else {
sound_lowhat.play();
}
}
function play_synth() {
if (boolean_loop === true) {
sound_synth.addEventListener("ended", function() {
this.currentTime = 0;
this.play();
}, false);
sound_synth.play();
} else {
sound_synth.play();
}
}
function play_beat() {
if (boolean_loop === true) {
sound_beat.addEventListener("ended", function() {
this.currentTime = 0;
this.play();
}, false);
sound_beat.play();
} else {
sound_beat.play();
}
}
HTML
<div id="musicboard">
<button class="btnMusic" onclick="play_highhat()">High Hat</button>
<button class="btnMusic" onclick="play_lowhat()">Low Hat</button>
<br>
<button class="btnMusic" onclick="play_synth()">Synth</button>
<button class="btnMusic" onclick="play_beat()">Beat</button>
</div>
<div id="options">
<button id="loopoption" onclick="sound_loop()">Loop</button>
<button onclick="audiostop()">Stop Music</button>
</div>
For a school task i've made a small soundboard with 4 sounds. I also have a button triggering a boolean to loop the sounds. The loop works fine, but whenever i stop all the sounds, if i click a sound that has been looped once before; it will loop again no matter the state of the boolean.

When you play a sound with looping option true what your code does is, is adds an event listener if loop condition is true. What you probably want to have is to check for the looping condition inside your listener.
Example of adding listener to one of the buttons.
sound_beat.addEventListener("ended", function() {
if (boolean_loop === true) {
this.currentTime = 0;
this.play();
}
}, false);
So, your code might look like this:
var boolean_loop = false;
var sound_highhat = new Audio("sound/sound_highhat.mp3");
var sound_lowhat = new Audio("sound/sound_lowhat.mp3");
var sound_synth = new Audio("sound/sound_synth.mp3");
var sound_beat = new Audio("sound/sound_beat.mp3");
function aListener = function() {
if (boolean_loop === true) {
this.currentTime = 0;
this.play();
}
};
// once you add listeners to the audio objects, those listeners stay there until they are removed so every "ended" event will trigger a listener
sound_highhat.addEventListener("ended", aListener, false);
sound_lowhat.addEventListener("ended", aListener, false);
sound_synth.addEventListener("ended", aListener, false);
sound_beat.addEventListener("ended", aListener, false);
function sound_loop() {
if (boolean_loop === false) {
document.getElementById("loopoption").innerHTML = "Loop (Active)";
boolean_loop = true;
} else if (boolean_loop === true) {
document.getElementById("loopoption").innerHTML = "Loop";
boolean_loop = false;
}
}
function audiostop() {
sound_highhat.pause()
sound_highhat.currentTime = 0.0;
sound_lowhat.pause()
sound_lowhat.currentTime = 0.0;
sound_synth.pause()
sound_synth.currentTime = 0.0;
sound_beat.pause()
sound_beat.currentTime = 0.0;
}
function play_highhat() {
sound_highhat.play();
}
function play_lowhat() {
sound_lowhat.play();
}
function play_synth() {
sound_synth.play();
}
function play_beat() {
sound_beat.play();
}

Related

How to add touch controls with keystrokes in 2048?

I have completed 2048 clone and its can be played on pc's and laptops but not on phones. I want to make it playble on both the devices is it possible to add touch event handler with keystrokes handler to the same version Or I have to make a complete different version for phone? if it can be done in the same version please tell how it can be done.
Thanks.
//Export Grid js
const GRID_SIZE = 4
const CELL_SIZE = 20
const CELL_GAP = 2
class Grid {
//making cells private is so that it can be only accesible in grid class
#cells
constructor(gridElement) {
gridElement.style.setProperty("--grid-size", GRID_SIZE)
gridElement.style.setProperty("--cell-size", `${CELL_SIZE}vmin`)
gridElement.style.setProperty("--cell-gap", `${CELL_GAP}vmin`)
this.#cells = createCellElements(gridElement).map((cellElement, index) => {
return new Cell(
cellElement,
index % GRID_SIZE,
Math.floor(index / GRID_SIZE)
)
})
}
get cells() {
return this.#cells
}
get cellsByRow() {
return this.#cells.reduce((cellGrid, cell) => {
cellGrid[cell.y] = cellGrid[cell.y] || []
cellGrid[cell.y][cell.x] = cell
return cellGrid
}, [])
}
get cellsByColumn() {
return this.#cells.reduce((cellGrid, cell) => {
cellGrid[cell.x] = cellGrid[cell.x] || []
cellGrid[cell.x][cell.y] = cell
return cellGrid
}, [])
}
get #emptyCells() {
return this.#cells.filter(cell => cell.tile == null)
}
// it will return which ever cell is empty
randomEmptyCell() {
const randomIndex = Math.floor(Math.random() * this.#emptyCells.length)
return this.#emptyCells[randomIndex]
}
}
class Cell {
#cellElement
#x
#y
#tile
#mergeTile
constructor(cellElement, x, y) {
this.#cellElement = cellElement
this.#x = x
this.#y = y
}
get x() {
return this.#x
}
get y() {
return this.#y
}
get tile() {
return this.#tile
}
set tile(value) {
this.#tile = value
if (value == null) return
this.#tile.x = this.#x
this.#tile.y = this.#y
}
get mergeTile() {
return this.#mergeTile
}
set mergeTile(value) {
this.#mergeTile = value
if (value == null) return
this.#mergeTile.x = this.#x
this.#mergeTile.y = this.#y
}
canAccept(tile) {
return (
this.tile == null ||
(this.mergeTile == null && this.tile.value === tile.value)
)
}
mergeTiles() {
if (this.tile == null || this.mergeTile == null) return
this.tile.value = this.tile.value + this.mergeTile.value
this.mergeTile.remove()
this.mergeTile = null
}
}
function createCellElements(gridElement) {
const cells = []
for (let i = 0; i < GRID_SIZE * GRID_SIZE; i++) {
const cell = document.createElement("div")
cell.classList.add("cell")
cells.push(cell)
gridElement.append(cell)
}
return cells
}
//Export Tile js
class Tile {
#tileElement
#x
#y
#value
// randomly set 2 or 4
constructor(tileContainer, value = Math.random() > 0.5 ? 2 : 4) {
this.#tileElement = document.createElement("div")
this.#tileElement.classList.add("tile")
tileContainer.append(this.#tileElement)
this.value = value
}
get value() {
return this.#value
}
set value(v) {
this.#value = v
this.#tileElement.textContent = v
// to determine how many times a number has be raised to power of 2
const power = Math.log2(v)
const backgroundLightness = 100 - power * 9
this.#tileElement.style.setProperty("--background-light", `${backgroundLightness}%`)
this.#tileElement.style.setProperty("--text-light", `${backgroundLightness <= 50 ? 90 : 10}%`)
}
set x(value) {
this.#x = value
this.#tileElement.style.setProperty("--x", value)
}
set y(value) {
this.#y = value
this.#tileElement.style.setProperty("--y", value)
}
remove() {
this.#tileElement.remove()
}
waitForTransition(animation = false) {
return new Promise(resolve => {
this.#tileElement.addEventListener(
animation ? "animationend" : "transitionend",
resolve,
{
once: true,
}
)
})
}
}
//brain js
//import Grid from "./Grid.js";
//import Tile from "./Tile.js";
const board = document.getElementById("holder");
const grid = new Grid(board)
grid.randomEmptyCell().tile = new Tile(board)
grid.randomEmptyCell().tile = new Tile(board)
setupInput()
function setupInput() {
window.addEventListener("keydown", handleInput, { once: true })
}
async function handleInput(e) {
switch (e.key) {
case "ArrowUp":
if (!canMoveUp()) {
setupInput()
return
}
await moveUp()
break
case "ArrowDown":
if (!canMoveDown()) {
setupInput()
return
}
await moveDown()
break
case "ArrowLeft":
if (!canMoveLeft()) {
setupInput()
return
}
await moveLeft()
break
case "ArrowRight":
if (!canMoveRight()) {
setupInput()
return
}
await moveRight()
break
default:
setupInput()
return
}
grid.cells.forEach(cell => cell.mergeTiles())
const newTile = new Tile(board)
grid.randomEmptyCell().tile = newTile
if (!canMoveUp() && !canMoveDown() && !canMoveLeft() && !canMoveRight()) {
newTile.waitForTransition(true).then(() => {
alert("You lose")
})
return
}
setupInput()
}
function moveUp() {
return slideTiles(grid.cellsByColumn)
}
function moveDown() {
return slideTiles(grid.cellsByColumn.map(column => [...column].reverse()))
}
function moveLeft() {
return slideTiles(grid.cellsByRow)
}
function moveRight() {
return slideTiles(grid.cellsByRow.map(row => [...row].reverse()))
}
function slideTiles(cells) {
return Promise.all(
cells.flatMap(group => {
const promises = []
for (let i = 1; i < group.length; i++) {
const cell = group[i]
if (cell.tile == null) continue
let lastValidCell
for (let j = i - 1; j >= 0; j--) {
const moveToCell = group[j]
if (!moveToCell.canAccept(cell.tile)) break
lastValidCell = moveToCell
}
if (lastValidCell != null) {
promises.push(cell.tile.waitForTransition())
if (lastValidCell.tile != null) {
lastValidCell.mergeTile = cell.tile
} else {
lastValidCell.tile = cell.tile
}
cell.tile = null
}
}
return promises
})
)
}
function canMoveUp() {
return canMove(grid.cellsByColumn)
}
function canMoveDown() {
return canMove(grid.cellsByColumn.map(column => [...column].reverse()))
}
function canMoveLeft() {
return canMove(grid.cellsByRow)
}
function canMoveRight() {
return canMove(grid.cellsByRow.map(row => [...row].reverse()))
}
function canMove(cells) {
return cells.some(group => {
return group.some((cell, index) => {
if (index === 0) return false
if (cell.tile == null) return false
const moveToCell = group[index - 1]
return moveToCell.canAccept(cell.tile)
})
})
}
*,
*::before,
*::after {
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
body {
background-color: black;
display: flex;
margin: 0;
justify-content: center;
align-items: center;
height: 100vh;
font-size: 7.5vmin;
}
#holder {
display: grid;
background-color: #ccc;
position: relative;
grid-template-columns: repeat(var(--grid-size), var(--cell-size));
grid-template-rows: repeat(var(--grid-size), var(--cell-size));
gap: var(--cell-gap);
padding: var(--cell-gap);
border-radius: 1vmin;
}
.cell {
background-color: #aaa;
border-radius: 1vmin;
}
.tile {
position: absolute;
display: flex;
justify-content: center;
align-items: center;
width: var(--cell-size);
height: var(--cell-size);
border-radius: 1vmin;
top: calc(var(--y) * (var(--cell-size) + var(--cell-gap)) + var(--cell-gap));
left: calc(var(--x) * (var(--cell-size) + var(--cell-gap)) + var(--cell-gap));
font-weight: bold;
background-color: hsl(271, 50%, var(--background-light));
color: hsl(200, 25%, var(--text-light));
animation: wow 200ms ease-in-out;
transition: 100ms ease-in-out;
}
#keyframes wow {
0% {
opacity: .5;
transform: scale(0);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2048</title>
<link rel="stylesheet" href="game.css">
<script src="brain.js" type="module"></script>
</head>
<body>
<div id="holder">
</div>
</body>
</html>

How do I fade in text in a div, while simultaneously descrambling the text in JavaScript

How do I perform an animated transformation on text while performing a fade in effect during the animated transformation?
// ——————————————————————————————————————————————————
// TextScramble
// ——————————————————————————————————————————————————
class TextScramble {
constructor(elm, numWords) {
this.el = el
this.numWords = numWords;
this.chars = '!<>-_\\/[]{}—=+*^?#1234567890________'
this.update = this.update.bind(this)
}
setText(newText) {
const oldText = this.el.innerText
const length = Math.max(oldText.length, newText.length)
const promise = new Promise((resolve) => this.resolve = resolve)
this.queue = []
for (let i = 0; i < length; i++) {
const from = oldText[i] || ''
const to = newText[i] || ''
const start = Math.floor(Math.random() * 40)
const end = start + Math.floor(Math.random() * 40)
this.queue.push({ from, to, start, end })
}
cancelAnimationFrame(this.frameRequest)
this.frame = 0
this.update()
return promise
}
update() {
let output = ''
let complete = 0
for (let i = 0, n = this.queue.length; i < n; i++) {
let { from, to, start, end, char } = this.queue[i]
if (this.frame >= end) {
complete++
output += to
} else if (this.frame >= start) {
if (!char || Math.random() < 0.28) {
char = this.randomChar()
this.queue[i].char = char
}
output += `<span class="dud">${char}</span>`
} else {
output += from
}
}
this.el.innerHTML = output
if (complete === this.queue.length) {
this.resolve()
}
else {
this.frameRequest = requestAnimationFrame(this.update)
this.frame++
}
}
randomChar() {
return this.chars[Math.floor(Math.random() * this.chars.length)]
}
}
// ——————————————————————————————————————————————————
// Example
// ——————————————————————————————————————————————————
const phrases = {
'Coding' : 'none',
'With' : 'none',
'Muhammad': 'none',
'Coding With Muhammad' : 'fade'
}
let phraseValues = Object.keys(phrases);
const el = document.querySelector('.text')
const fx = new TextScramble(el, phraseValues.length)
let counter = 0
let animation = phraseValues[0];
let animate = () => {
return function(callback) {
document.querySelector(".text").animate([
// keyframes
{ opacity: '0' },
{ opacity: '1' }
], {
// timing options
duration: 3500,
iterations: 1
});
callback();
}
}
const next = () => {
fx.setText(phraseValues[counter]).then(() => {
if (counter <= phraseValues.length)
setTimeout(next, 800)
else {
animation = phrases[phraseValues[counter]]
setTimeout(animate(next), 800)
}
})
counter = (counter + 1) % phraseValues.length
}
next()
html, body {
font-family: 'Roboto Mono', monospace;
background: #212121;
height: 100%;
}
.container {
height: 100%;
width: 100%;
justify-content: center;
align-items: center;
display: flex;
}
.text {
font-weight: 100;
font-size: 28px;
color: #FAFAFA;
}
.dud {
color: #757575;
}
.fadeIn {
animation: fade 10s;
}
<div class="container">
<div class="text"></div>
</div>
I was very close:
I moved the callback invocation statement above the closure return statement below it. I left the animation keyframes as is.
Finally I modified the setTimeout in the phrase to be animated, to be as follows:
I placed a next and animate as callbacks in the setTimeout together to be called back in cascade sequence.
I used a anonymous function definition using arrow notation.
On animate (the function I wrote) I passed in the fx.update function definition as the callback, and invoked the closure function returned animate as the Higher Order Function, like so.
See Results!
// ——————————————————————————————————————————————————
// TextScramble
// ——————————————————————————————————————————————————
class TextScramble {
constructor(elm, numWords) {
this.el = el
this.numWords = numWords;
this.chars = '!<>-_\\/[]{}—=+*^?#1234567890________'
this.update = this.update.bind(this)
}
setText(newText) {
const oldText = this.el.innerText
const length = Math.max(oldText.length, newText.length)
const promise = new Promise((resolve) => this.resolve = resolve)
this.queue = []
for (let i = 0; i < length; i++) {
const from = oldText[i] || ''
const to = newText[i] || ''
const start = Math.floor(Math.random() * 40)
const end = start + Math.floor(Math.random() * 40)
this.queue.push({ from, to, start, end })
}
cancelAnimationFrame(this.frameRequest)
this.frame = 0
this.update()
return promise
}
update = () => {
let output = ''
let complete = 0
for (let i = 0, n = this.queue.length; i < n; i++) {
let { from, to, start, end, char } = this.queue[i]
if (this.frame >= end) {
complete++
output += to
} else if (this.frame >= start) {
if (!char || Math.random() < 0.28) {
char = this.randomChar()
this.queue[i].char = char
}
output += `<span class="span">${char}</span>`
} else {
output += from
}
}
this.el.innerHTML = output
if (complete === this.queue.length) {
this.resolve()
}
else {
this.frameRequest = requestAnimationFrame(this.update)
this.frame++
}
}
randomChar() {
return this.chars[Math.floor(Math.random() * this.chars.length)]
}
}
// ——————————————————————————————————————————————————
// Example
// ——————————————————————————————————————————————————
const phrases = {
'Coding' : 'none',
'With' : 'none',
'Muhammad': 'none',
'Coding With Muhammad' : 'fade'
}
let phraseValues = Object.keys(phrases);
const el = document.querySelector('.text')
const fx = new TextScramble(el, phraseValues.length)
let counter = 0
let animation = phraseValues[0];
let animate = (callback) => {
callback();
return function() {
document.querySelector(".text").animate([
// keyframes
{ opacity: '0' },
{ opacity: '1' }
], {
// timing options
duration: 3500
});
}
}
const next = () => {
fx.setText(phraseValues[counter]).then(() => {
if (counter < phraseValues.length-1)
setTimeout(next, 800)
else {
setTimeout(() => {next, animate(next, fx.update)()}, 800)
}
})
counter = (counter + 1) % phraseValues.length
}
next()
html, body {
font-family: 'Roboto Mono', monospace;
background: #212121;
height: 100%;
}
.container {
height: 100%;
width: 100%;
justify-content: center;
align-items: center;
display: flex;
}
.text {
font-weight: 100;
font-size: 28px;
color: #FAFAFA;
}
.dud {
color: #757575;
}
<div class="container">
<div class="text"></div>
</div>

Simple Javascript button 2 in 1

Hi im just having some issues,
Im trying to make this text blink with just one button click
So Click ON
And also Click Acts as OFF ( If clicks value is set to on which is 1 )
Im pretty new to JS any help would be appreciated
var Blinker = {
interval: null,
start: function() {
if (this.interval) return;
this.interval = setInterval(function() {
$('#demo').toggle();
}, 250);
},
stop: function() {
clearInterval(this.interval);
$('#demo').show();
this.interval = null;
}
}
//Initialize blink status.
var blinkStatus = 1;
//Check if status is changed, and run/stop blinking.
setInterval(function() {
if (blinkStatus == 1) {
Blinker.start();
}
else {
Blinker.stop();
}
}, 250);
$('#start').on('click', function() {
blinkStatus = 1;
});
$('#stop').on('click', function() {
blinkStatus = 0;
});
<h1 id="demo">PAUSE</h1>
<button id="start">Start</button>
<button id="stop">Stop</button>
Try this code. This toggles blinking with a single button.
HTML:
<div class="text-container">
<h1 id="demo">PAUSE</h1>
</div>
<button id="toggle-button">Start</button>
CSS:
.hide {
display: none;
}
.text-container {
height: 17px;
}
JS:
var Blinker = {
interval: null,
start: function() {
if (this.interval) return;
this.interval = setInterval(function() {
$('#demo').toggleClass('hide');
}, 250);
},
stop: function() {
clearInterval(this.interval);
$('#demo').removeClass('hide');
this.interval = null;
}
}
//Initialize blink status.
var blinkStatus = 0;
//Check if status is changed, and run/stop blinking.
setInterval(function() {
if (blinkStatus == 1) {
$('#toggle-button').text('Stop');
Blinker.start();
}
else {
$('#toggle-button').text('Start');
Blinker.stop();
}
}, 250);
$('#toggle-button').on('click', function() {
if (blinkStatus) {
blinkStatus = 0;
} else {
blinkStatus = 1;
}
});
I've edited your code slightly, basing on your request on the comment.
//Initialize blink status.
var blinkStatus = false;
//Check if status is changed, and run/stop blinking.
var blinker, visibility;
$('#button').on('click', function() {
blinkStatus = !blinkStatus;
if(blinkStatus){
blinker = setInterval(function() {
visibility = $("#demo").css('visibility');
if(visibility == 'hidden'){
$("#demo").css('visibility', 'visible');
}else{
$("#demo").css('visibility', 'hidden');
}
}, 500);
$("#button").text('Stop');
}else{
clearInterval(blinker);
$("#button").text('Start');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="demo">PAUSE</h1>
<button id="button">Start</button>

JS/Jquery - Parallax Scrolling Effect lagging and slow

I have a parallax function for a slide section of my page with 3 background images. For some reasons it is appearing quite laggy and slow when I scroll and sometimes it's hard to scroll to the 3rd background image or if I'm already at 3rd background I can't seem to scroll up again. If I scrolled up to the first background I seem to be stuck on this section and I can't go to the section above it. Not sure where I went wrong.
Here's my js:
(function ($) {
var types = ['DOMMouseScroll', 'mousewheel'];
if ($.event.fixHooks) {
for (var i = types.length; i;) {
$.event.fixHooks[types[--i]] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function () {
if (this.addEventListener) {
for (var i = types.length; i;) {
this.addEventListener(types[--i], handler, false);
}
} else {
this.onmousewheel = handler;
}
}
, teardown: function () {
if (this.removeEventListener) {
for (var i = types.length; i;) {
this.removeEventListener(types[--i], handler, false);
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function (fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
}
, unmousewheel: function (fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event
, args = [].slice.call(arguments, 1)
, delta = 0
, returnValue = true
, deltaX = 0
, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
if (orgEvent.wheelDelta) {
delta = orgEvent.wheelDelta / 120;
}
if (orgEvent.detail) {
delta = -orgEvent.detail / 3;
}
deltaY = delta;
if (orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS) {
deltaY = 0;
deltaX = -1 * delta;
}
if (orgEvent.wheelDeltaY !== undefined) {
deltaY = orgEvent.wheelDeltaY / 120;
}
if (orgEvent.wheelDeltaX !== undefined) {
deltaX = -1 * orgEvent.wheelDeltaX / 120;
}
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
})(jQuery);
var Parallax = {
utils: {
doSlide: function (section) {
var top = section.position().top;
$('#section-wrapper').stop().animate({
top: -top
}, 600, 'linear', function () {
section.addClass('slided').siblings('div.section').removeClass('slided');
});
}
}
, fn: {
setHeights: function () {
$('div.section').height($(window).height());
}
, onSiteScroll: function () {
var section = null;
$('#section-wrapper').mousewheel(function (event, delta) {
event.preventDefault();
if (delta < 0) {
section = ($('.slided').length) ? $('.slided') : $('#section-1');
var next = (section.next().length) ? section.next() : $('#section-1');
Parallax.utils.doSlide(next);
} else if (delta > 0) {
section = ($('.slided').length) ? $('.slided') : $('#section-1');
var prev = (section.prev().length) ? section.prev() : $('#section-1');
Parallax.utils.doSlide(prev);
}
});
}
},
init: function () {
for (var prop in this.fn) {
if (typeof this.fn[prop] === 'function') {
this.fn[prop]();
}
}
}
};
Parallax.init();
The css here:
#site {
width: 100%;
height: 100%;
min-height: 100%;
}
#section-wrapper {
position: relative;
width: 100%;
height: 100%;
min-height: 100%;
}
div.section {
width: 100%;
position: relative;
height: 100%;
min-height: 100%;
}
#section-1 {
background: url("../img/teavana/slide1.png");
}
#section-2 {
background: url("../img/teavana/slide2.png");
}
#section-3 {
background: url("../img/teavana/slide3.png");
}
And this is the html for the section:
<div id="site">
<div id="section-wrapper">
<div class="section" id="section-1"></div>
<div class="section" id="section-2"></div>
<div class="section" id="section-3"></div>
</div>
</div>

generating a number of divs at a time in jQuery

I'm trying to make a game with jquery where bullets are appended using a function. So far bullets are generating whenever I press spacebar but I want to generate bullets like 3-5 stacks. 3-5 bullets will be generated and then a short break then again 3-5 bullets will be generated and the process continues. Bullets are appended as div element. Here are the codes,
function generateBullet() {
var Player = $('#player');
var PlayerLeft = Player.offset().left;
var PlayerTop = Player.offset().top - 50;
var appendingValue = "<div class='bulletID' style=' position: absolute; left: 250px; top: 250px;'></div>";
var appendSize = $('.bulletID').size();
if (appendSize >= 3) {
$('#content').delay(5000).append(appendingValue);
} else {
$('#content').append(appendingValue);
}
}
function animateBullet() {
var bulletID = $('.bulletID');
bulletID.each(function () {
var nowTop = $(this).offset().top;
$(this).css("top", nowTop - 25);
});
}
var keys = {}
$(document).keydown(function (e) {
keys[e.keyCode] = true;
});
$(document).keyup(function (e) {
delete keys[e.keyCode];
});
function shoot() {
var Player = $('#player');
for (var direction in keys) {
if (!keys.hasOwnProperty(direction)) continue;
if (direction == 32) {
generateBullet();
}
}
}
JSFIDDLE DEMO : http://jsfiddle.net/ygz5wo7r/1/
I'm not getting any more idea how to do this. Your help will be really appreciated. TnQ.
Try this
I added
return false;
after
if (appendSize >= 3) {
...
and
parseInt($(this).css("top"))< 0 && $(this).remove();
to animateBullet()
to remove the bullets when they leave the screen
you can count how many bullets you fired each chain, and block the gun if chain reaches 3-5 bullets. and then using a timeout you can unblock the gun. that way you have control over the interval between bullet chains:
Fixed Fiddle
var bullets_chain = 0;
var block_gun = false;
function generateBullet() {
if (block_gun == false) {
var Player = $('#player');
var PlayerLeft = Player.offset().left;
var PlayerTop = Player.offset().top - 50;
var appendingValue = "<div class='bulletID' style=' position: absolute; left: 250px; top: 250px;'></div>";
bullets_chain++;
if (bullets_chain >= 5) {
block_gun = true;
bullets_chain = 0;
setTimeout(function () {
block_gun = false;
}, 500);
}
$('#content').append(appendingValue);
}
}
function animateBullet() {
var bulletID = $('.bulletID');
bulletID.each(function () {
var nowTop = $(this).offset().top;
if (nowTop < 0) {
$(this).remove();
} else {
$(this).css("top", nowTop - 25);
}
});
}
var keys = {}
$(document).keydown(function (e) {
if (block_gun == false) {
keys[e.keyCode] = true;
}
});
$(document).keyup(function (e) {
delete keys[e.keyCode];
});
function shoot() {
var Player = $('#player');
for (var direction in keys) {
if (!keys.hasOwnProperty(direction)) continue;
if (direction == 32) {
generateBullet();
}
}
}
$(document).ready(function () {
setInterval(shoot, 50);
setInterval(animateBullet, 100);
});

Categories

Resources