trying to understand function construction - javascript

I am trying to understand function construction so I can cut down on my repeated code. All the snippets I have see deal with returning values and was hoping someone could shed some light on why this doesn't work.
<div id = 'box1' style = 'background-color: green; height: 100px; width: 50px' >
</div>
var box = $('#box1');
function pushCard(x){
if(x.style.opacity == 0.5){
x.style.opacity = 1;
}
else {
x.style.opacity = 0.5;
}
}
box.click(pushCard(box));

You don't want to call the function as you pass it. You can just pass the function, then when you click it will pass the event. The element is the event target
var box = $('#box1');
function pushCard(event) {
let x = event.target
if (x.style.opacity == 0.5) {
x.style.opacity = 1;
} else {
x.style.opacity = 0.5;
}
}
box.click(pushCard);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='box1' style='background-color: green; height: 100px; width: 50px'>
</div>
You can also use this to get the clicked object:
var box = $('#box1');
function pushCard() {
if (this.style.opacity == 0.5) {
this.style.opacity = 1;
} else {
this.style.opacity = 0.5;
}
}
box.click(pushCard);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='box1' style='background-color: green; height: 100px; width: 50px'>
</div>

Related

How to wait for the function to end before start the function again

How to wait for my first function to end before I can click "Click me" button again. I have been searching for a way to let my function end first before I can let the new function run again.
document.getElementById("myBtn").addEventListener("click", myFunction);
setTimeout(function() {
myFunction();
}, 3000);
var id = null;
function myFunction() {
var elem = document.getElementById("myAnimation");
var pos = 0;
clearInterval(id);
id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<h2>JavaScript addEventListener()</h2>
<button id="myBtn">Click Me</button>
<div id="myContainer">
<div id="myAnimation"></div>
If we disable and enable the button in the correct place, it will work quite nicely
I also cleaned up the code a bit to make it more contained.
window.addEventListener('DOMContentLoaded', () => {
const myBtn = document.getElementById("myBtn");
const elem = document.getElementById("myAnimation");
let id = null;
let pos = 0;
const frame = () => {
if (pos == 350) {
clearInterval(id);
myBtn.disabled = false;
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
const myFunction = () => {
pos = 0;
clearInterval(id);
id = setInterval(frame, 10);
myBtn.disabled = true;
}
id = setTimeout(myFunction, 3000);
myBtn.addEventListener("click", myFunction);
});
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<h2>JavaScript addEventListener()</h2>
<button id="myBtn">Click Me</button>
<div id="myContainer">
<div id="myAnimation"></div>
</div>
As a first implementation you could disable the button before you start the animation, and you only enable it after you are done
var myBtn = document.getElementById("myBtn")
myBtn.addEventListener("click", myFunction);
setTimeout(function() {
myFunction();
}, 3000);
var id = null;
function myFunction() {
var elem = document.getElementById("myAnimation");
var pos = 0;
clearInterval(id);
id = setInterval(frame, 10);
// disable the button
myBtn.disabled = true;
function frame() {
if (pos == 350) {
clearInterval(id);
// enable the button again
myBtn.disabled = false;
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<h2>JavaScript addEventListener()</h2>
<button id="myBtn">Click Me</button>
<div id="myContainer">
<div id="myAnimation"></div>
You should disable your button during your function.
edited: If you don't want to disable maybe with a lock.
document.getElementById("myBtn").addEventListener("click", myFunction);
setTimeout(function() {
myFunction();
}, 3000);
var id = null;
var lock = false;
function myFunction() {
if(!lock){
lock = true;
var elem = document.getElementById("myAnimation");
var pos = 0;
clearInterval(id);
id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
lock = false;
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
}
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<h2>JavaScript addEventListener()</h2>
<button id="myBtn">Click Me</button>
<div id="myContainer">
<div id="myAnimation"></div>
edited: Try making your animation with CSS it's a better practice.
let sum = 0;
const x = 10;
async function firstFunction() {
for (i = 0; i < x; i++) {
sum = sum + i;
}
return sum;
}
async function secondFunction() {
await firstFunction();
console.log('After firstFunction executed sum is', sum);
}
secondFunction();

else if not working in KeyCode events javascript

I am trying to make me character moving left and up and I think jump() and slideLeft()
functions are working properly and the problem is in the controller(e) function (else if (e.KeyCode===37)) . The first function is avaible but it isn't able to acces the second conditon function. Also, I would want to make the grid solid after I will make an slideRight() similar function ,so if my character is jumping on it, the platform would sustain the square . Has anyone any ideea for either of my questions ?
Code snippet:
var square = document.querySelector('.square');
var grid = document.querySelector('.grid');
var bottom = 0;
let isJumping = false;
let isGoingLeft = false;
var newBottom;
let left = 0;
let leftTimerId;
function jump() {
if (isJumping) return
let timerUpId = setInterval(function() {
if (bottom > 250) {
clearInterval(timerUpId);
let timerDownId = setInterval(function() {
if (bottom < 0) {
clearInterval(timerDownId);
isJumping = false;
}
bottom -= 5;
square.style.bottom = bottom + 'px';
}, 20)
}
isJumping = true;
bottom += 30;
square.style.bottom = bottom + 'px';
}, 20)
}
function slideLeft() {
console.log('da');
isGoingLeft = true;
leftTimerId = setInterval(function() {
left -= 5;
square.style.left = left + 'px';
}, 20)
}
function controller(e) {
if (e.keyCode === 32)
jump();
else if (e.KeyCode === 37)
slideLeft();
}
document.addEventListener('keydown', controller);
.grid {
position: absolute;
background-color: chartreuse;
height: 20px;
width: 500px;
bottom: 100px;
left: 100px;
}
.square {
position: absolute;
background-color: darkblue;
height: 100px;
width: 100px;
bottom: 0px;
left: 150px;
}
`
<div class="grid"></div>
<div class="square"></div>
EDIT:
There is a typo:
The second time you've written KeyCode
function controller(e) {
if(e.keyCode===32) {
jump();
}
else if(e.keyCode===37) {
slideLeft();
}
}
I don't really understand what you mean by the second part of your question. If you want a character to have the ability to jump on a square, you'll have to implement a collision detection. Something like this:
if ( isNotOnGround() ) {
fall()
}

Carousel that automatically changes image [JS]

I'm trying to make a carousel that after 3 seconds changes image.
I got 3 images as slide1, slide2, slide3
and thanks to the methods change1,change2,change3 changes image.
I would like to automate everything like this:
function time(change1, change2, change3) {
this.change1 = change1;
this.change2 = change2;
this.change3 = change3;
t = setInterval(change1 && change2 && change3, 3000); //obviously it doesn't work.
}
/*
---------------ANOTHER METHOD-----------------
*/
function time() {
t = setInterval(check, 3000);
}
function check() {
if (slide1.style.display = "inline-block") {
change2();
} else if (slide2.style.display = "inline-block") {
change3();
} else {
change1();
}
}
but i don't know how
Any ideas?
well that is an easy job, here is a simple example on how you could do it
I used jq but you will get the idee. if you want only js that let me know will do it to
/// use jq for batter effekt
var sliders = $(".container > div");
var current;
function change() {
if (!current)
current = sliders.first();
else {
current.hide("fast");
current = current.next();
}
if (current.length == 0)
current = sliders.first();
current.show();
}
setInterval(change, 2000);
.container {
display: flex;
border: 1px solid #CCC;
}
.container>div {
width: 100%;
min-height: 100px;
}
.container>div:not(:first-child){
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div style="background:red;"></div>
<div style="background:green"></div>
<div style="background:blue"></div>
</div>

trying to understand "Simon" game

I'm Working on Simon game. I need help with understanding how to reference an id and creating an action without a click but say with page refresh.
1) on screen refresh (the start of the game), I CAN randomize the color id chosen...and save it in a var called randomColorChosen... but I can NOT figure out how to make that var randomColorChosen, make the same actions as if they were a clicked on button like my code at the bottom.
2) My btn click and animate color and play sound... work fine,
I have tried many iterations of my newbie coding...
Now I'm just guessing and here is it's last state....
... random Color Chosen works... its what's next I need help (explanations on)
... $(document).keydown(function(event) {} works and tested with an alert()
... but the rest, down until my but clicks, I have changed so many times my head is spinning. Help my understand where I am dumb AF! lol
... user btn click event action and sound... works fine!
Here is my code so far:
buttonColors=["btn green","btn red", "btn yellow", "btn blue"];
randomColorChosen=buttonColors[Math.floor(Math.random() * (buttonColors.length))];
$(document).keydown(function(event) {
setTimeout(2000);
$("#id").attr(function(randomColorChosen){
$(this).fadeOut(100).fadeIn(100);
var myPadColor = $(this).attr("#id");
});
});
$(document).ready(function() {
$(".btn").click(function(event) {
$(this).fadeOut(100).fadeIn(100);//when a "this" button is clicked .fadeOut(100).fadeIn(100);
var myPadColor = $(this).attr("class");
;
switch (myPadColor) {
case "btn green":
var greenPad = new Audio('sounds/green.mp3');
greenPad.play();
break;
case "btn red":
var redPad = new Audio('sounds/red.mp3');
redPad.play();
break;
case "btn yellow":
var yellowPad = new Audio('sounds/yellow.mp3');
yellowPad.play();
break;
case "btn blue":
var bluePad = new Audio('sounds/blue.mp3');
bluePad.play();
break;
default:
console.log(myPadColor);
}
});
});
It was a little unclear what you are trying to accomplish. I created an example with some possible improved code.
$(function() {
var seq = [];
var player = [];
var c;
var round = 0;
var sounds = [
new Audio('sounds/green.mp3'),
new Audio('sounds/red.mp3'),
new Audio('sounds/yellow.mp3'),
new Audio('sounds/blue.mp3')
];
function getRandom() {
return Math.floor(Math.random() * 4);
}
function initSeq(n) {
for (var i = 0; i < n; i++) {
seq.push(getRandom());
}
}
function flash(b) {
//console.log("Flashing Button " + b);
var btn = $("#game-board .btn").eq(b);
btn.fadeTo(300, 1.0, function() {
btn.fadeTo(300, 0.35);
});
sounds[b].play();
}
function endGame() {
$("#game-board").hide();
$("h1").show();
$("h1").after("<h2>Gome Over. Score: " + player.length + "</h2>");
}
function waitUserInput() {
c = setInterval(endGame, 10 * 1000);
}
function playSequence(x) {
if (x == 0 || x == undefined) {
x = 20;
}
$.each(seq, function(i, s) {
if (i < x) {
flash(s);
}
});
}
function nextRound() {
playSequence(++round);
}
function initGame() {
initSeq(20);
player = [];
c = null;
round = 0;
nextRound();
}
$(document).keydown(function(event) {
$("h1").hide();
$("#game-board").show();
initGame();
});
$("#game-board .btn").click(function(event) {
var i = $(this).index();
flash(i);
player.push(i);
});
$("#playSeq").click(function() {
var p = $(this).next().val();
console.log("TEST: Play Sequence to " + p + " Position.");
if (seq.length == 0) {
initSeq(20);
$("#game-board").show();
}
//console.log("TEST", seq);
playSequence(p);
});
});
#game-board {
width: 410px;
white-space: normal;
}
.btn {
width: 200px;
height: 200px;
display: inline-block;
opacity: 0.35;
padding: 0;
margin: 0;
border: 0;
}
.green {
background: green;
border-radius: 199px 0 0 0;
}
.red {
border: 0;
background: red;
border-radius: 0 199px 0 0;
}
.yellow {
border: 0;
background: yellow;
opacity: 0.65;
border-radius: 0 0 0 199px;
}
.blue {
border: 0;
background: blue;
opacity: 0.65;
border-radius: 0 0 199px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test-bar">
<button id="playSeq">Play To</button> <input type="number" value="1" style="width: 2.5em;" />
</div>
<h1>Press Any Key to Begin.</h1>
<div id="game-board" style="display: none;">
<div class="btn green"></div>
<div class="btn red"></div>
<div class="btn yellow"></div>
<div class="btn blue"></div>
</div>

(HTML) JavaScript Collapsible Menu Error

http://jsfiddle.net/xNnQ5/
I am trying to use JavaScript (and HTML) to create a collapsible menu (c_menu) for my website. I would like it to be opened when the user clicks on the div menu_open, and to close when the user clicks menu_close. However, when I load the page, all that happens is the menu simply scrolls up, as if I have clicked menu_close, which I haven't. What should I do?
Code:
index.html (Only a snippet)
<style type = "text/css">
#c_menu {
position: absolute;
width: 435px;
height: 250px;
z-index: 2;
left: 6px;
top: 294px;
background-color: #0099CC;
margin: auto;
</style>
<div id="menu_open"><img src="images/open.jpg" width="200" height="88" /></div>
<input type="button" name="menu_close" id="menu_close" value="Close"/>
<div id="c_menu"></div>
<script type = "text/javascript" src = "menu.js"> </script>
menu.js (Full code)
document.getElementById("c_menu").style.height = "0px";
document.getElementById("menu_open").onclick = menu_view(true);
document.getElementById("menu_close").onclick = menu_view(false);
function menu_view(toggle)
{
if(toggle == true)
{
document.getElementById("c_menu").style.height = "0px";
changeheight(5, 250, 0);
}
if(toggle == false)
{
document.getElementById("c_menu").height = "250px";
changeheight(-5, 0, 250);
}
}
function changeheight(incr, maxheight, init)
{
setTimeout(function () {
var total = init;
total += incr;
var h = total + "px";
document.getElementById("c_menu").style.height = h;
if (total != maxheight) {
changeheight(incr, maxheight, total);
}
}, 5)
}
Try this:
document.getElementById("menu_open").onclick = function() {menu_view(true)};
document.getElementById("menu_close").onclick = function() {menu_view(false)};
When you define the function with a parenthesis ( ...onclick = menu_view(true) ), the function is called automatically.
When you have a function with no parameters, you can use it like you did, but without the parenthesis:
document.getElementById("menu_open").onclick = menu_view;
document.getElementById("menu_close").onclick = menu_view;

Categories

Resources