Button with multi-tasks in javascript - javascript

how I can get a multifunction button in JS? For example:
the first click will move the button down, the next click will return it to the default place.
let caoButton = document.querySelector('.js-cao-2');
caoButton.style.position = 'absolute';
caoButton.style.top = '0';
caoButton.style.left = '0';
caoButton.addEventListener('click',() {
caoButton.style.top = 'unset';
caoButton.style.left = 'unset';
caoButton.style.bottom = '0';
caoButton.style.right = '0';
});

Agree with #charlietfl
let caoButton = document.querySelector('.js-cao-2');
caoButton.addEventListener('click',()=>caoButton.classList.toggle("moveDown"));
.js-cao-2{
position: absolute;
top: 0;
left: 0;
}
.moveDown {
top: unset;
left: unset;
bottom: 0;
right: 0;
}
<div style="height: 100vh">
<button class="js-cao-2" >Move me</button>
</div>
In case you wish to do something more that just manipulate the css and you must use JavaScript, you can also do something like:
let caoButton = document.querySelector('.js-cao-2');
caoButton.addEventListener('click',firstFunctionality);
function firstFunctionality(){
caoButton.removeEventListener('click', firstFunctionality)
caoButton.addEventListener('click',secondFunctionality);
//do stuff here
}
function secondFunctionality(){
caoButton.removeEventListener('click', secondFunctionality)
caoButton.addEventListener('click', firstFunctionality);
//do something different here
}

This will trigger multiple actions on the button.
let caoButton = document.querySelector('.js-cao-2');
const allTasks = (function* makeTaskGetter(){
const tasks = [
'js-cao-2-down',
'js-cao-2-right',
'js-cao-2-up',
'js-cao-2-left'
];
for (const task of tasks) { yield task; }
})();
caoButton.addEventListener('click', e => {
const { value : task } = allTasks.next();
caoButton.classList.add(task);
});
.js-cao-2 {
position: absolute;
}
.js-cao-2-down {
top: 100px;
}
.js-cao-2-right {
left: 100px;
}
.js-cao-2-up {
top: 10px;
}
.js-cao-2-left {
left: 10px;
}
<button class="js-cao-2">Click Me</button>
Also consider using transform: translate depending on your use case.

Related

how to remove the quotes or get element from this (javascript)

As topic, how can I remove the quote in the picuture below or get the img element from this?
(https://i.stack.imgur.com/kdPAP.png)
I m new to javascript and start making an image slider that can pop up a window while clicked to the image.
I cloned the li object which is clicked, and try to open it in the new window, it do work but how can I get the img only without the li?
Right now i m trying to call the cloned this object with innerHTML, but it shows the img element with quote, is there any way to remove the quote?
the quote that i want to remove
first time ask a question in here, if i violate any rules in the post, i delete the post, sorry for causing any inconvenience.
Here is the code
<!DOCTYPE html>
<html>
<head>
<style>
.risuto1 {
max-width: 480px;
max-height: 270px;
margin: auto;
position: relative;
}
ul {
list-style-type: none;
margin: auto;
padding: 0;
}
.aitemu>img {
max-width: 100%;
}
.aitemu {
display: none;
position: relative;
}
.aitemu.akutibu {
display: block;
}
.risuto1>.mae,
.tsugi {
width: auto;
height: auto;
padding: 20px;
top: 102.6px;
position: absolute;
cursor: pointer;
background-color: red;
}
.risuto1>.tsugi {
left: 431.8px;
}
</style>
</head>
<body>
<script>
var risuto1 = document.createElement("div");
risuto1.classList.add("risuto1");
document.body.appendChild(risuto1);
var suraidaaitemu = document.createElement("ul");
suraidaaitemu.classList.add("suraidaaitemu");
risuto1.appendChild(suraidaaitemu);
var imejisosurisuto = ["https://pbs.twimg.com/media/CGGc3wKVEAAjmWj?format=jpg&name=medium", "https://pbs.twimg.com/media/EYCXvuzU8AEepqD?format=jpg&name=large", "https://s3-ap-northeast-1.amazonaws.com/cdn.bibi-star.jp/production/imgs/images/000/668/074/original.jpg?1626914998", "https://livedoor.blogimg.jp/rin20064/imgs/7/3/73251146.jpg", "https://www.tbs.co.jp/anime/oregairu/character/img/chara_img_02.jpg"]
//var imejirisuto=[]
for (var n = 0; n < imejisosurisuto.length; n++) {
var imeji = document.createElement("img");
imeji.src = imejisosurisuto[n];
var aitemu = document.createElement("li");
aitemu.classList.add("aitemu");
suraidaaitemu.appendChild(aitemu);
aitemu.appendChild(imeji);
aitemu.onclick=atarashivindou;
}
var akutibunasaishonoko = document.querySelector(".suraidaaitemu").firstChild;
akutibunasaishonoko.classList.add("akutibu");
var mae = document.createElement("div");
mae.classList.add("mae");
mae.innerHTML = "&#10094";
risuto1.appendChild(mae);
var tsugi = document.createElement("div");
tsugi.classList.add("tsugi");
tsugi.innerHTML = "&#10095";
risuto1.appendChild(tsugi);
var tensuu = 0;
var suraido = document.querySelector(".suraidaaitemu").children;
var gokeisuraido = suraido.length;
tsugi.onclick = function () {
Tsugi("Tsugi");
}
mae.onclick = function () {
Tsugi("Mae");
}
function Tsugi(houkou) {
if (houkou == "Tsugi") {
tensuu++;
if (tensuu == gokeisuraido) {
tensuu = 0;
}
}
else {
if (tensuu == 0) {
tensuu = gokeisuraido - 1;
}
else {
tensuu--;
}
}
for (var i = 0; i < suraido.length; i++) {
suraido[i].classList.remove("akutibu");
}
suraido[tensuu].classList.add("akutibu");
}
function atarashivindou(){
var Atarashivindou = window.open("", "_blank", "width: 1000px, max-height: 562.5px");
var kakudaigazou=document.createElement("div");
kakudaigazou.classList.add("kakudaigazou");
Atarashivindou.document.body.appendChild(kakudaigazou);
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
}
</script>
</body>
.innerHTML is a string. You don't want to append a string, but the element. So change this:
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
...to this:
var koronimeji=this.querySelector("img").cloneNode();
kakudaigazou.append(koronimeji);

I need to make a high-score list for this Javascript game

I hope you can give me a hand with this. My idea is to show a list of high-scores after the game is finished for a Doodle Jump project (javascript). The high-scores are presented successfully as you will see in my code, but the presentation is poor. Hence, I want to show them in a blank page, if possible using the same html. I will leave my code for you to reproduce the issue and help me. I thought about some document command, but you tell me.
Thanks in advance.
document.addEventListener('DOMContentLoaded', () => {
const grid = document.querySelector('.grid')
const doodler = document.createElement('div')
const unMutedIcon = document.createElement('div')
let doodlerLeftSpace = 50
let startPoint = 150
let doodlerBottomSpace = startPoint
let isGameOver = false
let platformCount = 5
let platforms = []
let upTimerid
let downTimerId
let isJumping = true
let isGoingLeft = false
let isGoingRight = false
let leftTimerId
let rightTimerId
let score = 0
let context
let musicIsPlaying = false
let copyRightMessage = " DoodleJump version by Santiago Hernandez \n all rights reserved \n Copyright © "
const NO_OF_HIGH_SCORES = 10;
const HIGH_SCORES = 'highScores';
function createDoodler() {
grid.appendChild(doodler)
doodler.classList.add('doodler')
doodlerLeftSpace = platforms[0].left
doodler.style.left = doodlerLeftSpace + 'px'
doodler.style.bottom = doodlerBottomSpace + 'px'
}
function control(e) {
if (e.key === "ArrowLeft") {
moveLeft()
} else if (e.key === "ArrowRight") {
moveRight()
} else if (e.key === "ArrowUp") {
moveStraight()
}
}
class Platform {
constructor(newPlatBottom) {
this.bottom = newPlatBottom
this.left = Math.random() * 315
this.visual = document.createElement('div')
const visual = this.visual
visual.classList.add('platform')
visual.style.left = this.left + 'px'
visual.style.bottom = this.bottom + 'px'
grid.appendChild(visual)
}
}
function createPlatforms() {
for (let i = 0; i < platformCount; i++) {
let platGap = 600 / platformCount
let newPlatBottom = 100 + i * platGap
let newPlatform = new Platform(newPlatBottom)
platforms.push(newPlatform)
console.log(platforms)
}
}
function movePlatforms() {
if (doodlerBottomSpace > 200) {
platforms.forEach(platform => {
platform.bottom -= 4
let visual = platform.visual
visual.style.bottom = platform.bottom + 'px'
if (platform.bottom < 10) {
let firstPlatform = platforms[0].visual
firstPlatform.classList.remove('platform')
platforms.shift()
score++
console.log(score)
console.log(platforms)
let newPlatform = new Platform(600)
platforms.push(newPlatform)
}
})
}
}
function jump() {
clearInterval(downTimerId)
isJumping = true
upTimerId = setInterval(function() {
doodlerBottomSpace += 20
doodler.style.bottom = doodlerBottomSpace + 'px'
if (doodlerBottomSpace > startPoint + 200) {
fall()
}
}, 30)
}
function fall() {
clearInterval(upTimerId)
isJumping = false
downTimerId = setInterval(function() {
doodlerBottomSpace -= 5
doodler.style.bottom = doodlerBottomSpace + 'px'
if (doodlerBottomSpace <= 0) {
gameOver()
}
platforms.forEach(platform => {
if ((doodlerBottomSpace >= platform.bottom) &&
(doodlerBottomSpace <= platform.bottom + 15) &&
((doodlerLeftSpace + 60) >= platform.left) &&
(doodlerLeftSpace <= (platform.left + 85)) &&
!isJumping
) {
console.log('landed')
startPoint = doodlerBottomSpace
jump()
}
})
}, 30)
}
function moveLeft() {
if (isGoingRight) {
clearInterval(rightTimerId)
isGoingRight = false
}
isGoingLeft = true
leftTimerId = setInterval(function() {
if (doodlerLeftSpace >= 0) {
doodlerLeftSpace -= 5
doodler.style.left = doodlerLeftSpace + 'px'
} else moveRight()
}, 30)
}
function moveRight() {
if (isGoingLeft) {
clearInterval(leftTimerId)
isGoingLeft = false
}
isGoingRight = true
rightTimerId = setInterval(function() {
if (doodlerLeftSpace <= 340) {
doodlerLeftSpace += 5
doodler.style.left = doodlerLeftSpace + 'px'
} else moveLeft()
}, 30)
}
function moveStraight() {
isGoingRight = false
isGoingLeft = false
clearInterval(rightTimerId)
clearInterval(leftTimerId)
}
function gameOver() {
console.log('GAME OVER')
isGameOver = true
try {
context.pause()
while (grid.firstChild) {
grid.removeChild(grid.firstChild)
}
grid.innerHTML = score
clearInterval(upTimerId)
clearInterval(downTimerId)
clearInterval(leftTimerId)
clearInterval(rightTimerId)
} catch (err) {
console.log('there was an error at gameover')
while (grid.firstChild) {
grid.removeChild(grid.firstChild)
}
grid.innerHTML = score
clearInterval(upTimerId)
clearInterval(downTimerId)
clearInterval(leftTimerId)
clearInterval(rightTimerId)
}
checkHighScore()
}
function saveHighScore(score, highScores) {
const name = prompt('You got a highscore! Enter name:');
const newScore = {
score,
name
};
// 1. Add to list
highScores.push(newScore);
// 2. Sort the list
highScores.sort((a, b) => b.score - a.score);
// 3. Select new list
highScores.splice(NO_OF_HIGH_SCORES);
// 4. Save to local storage
localStorage.setItem(HIGH_SCORES, JSON.stringify(highScores));
};
function checkHighScore() {
const highScores = JSON.parse(localStorage.getItem(HIGH_SCORES)) ? ? [];
const lowestScore = highScores[NO_OF_HIGH_SCORES - 1] ? .score ? ? 0;
if (score > lowestScore) {
saveHighScore(score, highScores); // TODO
showHighScores(); // TODO
}
}
function showHighScores() {
const highScores = JSON.parse(localStorage.getItem(HIGH_SCORES)) ? ? [];
const highScoreList = document.getElementById('highScores');
highScoreList.innerHTML = highScores.map((score) =>
`<li>${score.score} - ${score.name}</li>`
);
}
function start() {
if (!isGameOver) {
createPlatforms()
createDoodler()
setInterval(movePlatforms, 30)
jump()
document.addEventListener('keyup', control)
}
}
document.addEventListener('keypressed', control)
//attach to buttom
start()
//event listener to play music
document.addEventListener('keypress', function(e) {
if (e.keyCode == 32 || e.code == "Space") {
musicIsPlaying = true
context = new Audio("Music_level1.wav");
context.play()
context.loop = true
}
}) //end of event listener
})
.grid {
width: 400px;
height: 600px;
background-color: yellow;
position: relative;
font-size: 200px;
text-align: center;
background-image: url(bluesky_level1.gif);
background-size: contain;
background-repeat: no-repeat;
background-size: 400px 600px;
margin-right: auto;
margin-left: auto;
}
.doodler {
width: 60px;
height: 85px;
position: absolute;
background-image: url(mariobros_level1.png);
background-size: contain;
background-repeat: no-repeat;
background-size: 60px 85px;
filter: brightness(1.1);
mix-blend-mode: multiply;
}
#audio {
display: none
}
.platform {
width: 85px;
height: 15px;
position: absolute;
background-image: url(platform_tramp_level1.png);
background-size: contain;
background-repeat: no-repeat;
background-size: 85px 15px;
}
.volumeIcon {
width: 30px;
height: 30px;
position: absolute;
top: 570px;
background-image: url(volumeIconMuted.png);
background-size: contain;
background-repeat: no-repeat;
background-size: 30px 30px;
}
.unmutedIcon {
width: 30px;
height: 30px;
position: absolute;
top: 570px;
background-image: url(VolumeIcon.png);
background-size: contain;
background-repeat: no-repeat;
background-size: 30px 30px;
}
#highScores {
width: 400px;
height: 300px;
font-size: 30px;
font-family: "Georgia", "Times New Roman";
text-align: center;
position: absolute;
}
<ol id="highScores"></ol>
<div class="grid">
<div class="volumeIcon"></div>
</div>
I included what I think will reproduce the situation. Hope this helps you help me.
Why not just put:
<ol id = "highScores"></ol>
within a <div> and give that a class that has display: none initally? Like this:
<div class="high-scores-container">
<ol id = "highScores"></ol>
</div>
.high-scores-container {
display: none;
height: 100%;
}
Then when you run your showHighScores() function, grab the high-scores-container div and change the display to block and then at the same time, grab the grid div and set that to display: none. That will give you the effect of displaying your high scores on a separate page but you're just doing so with JS/CSS.

How do I programatically change a picture inside a div?

Here there is full code as you guys can see.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Collage</title>
</head>
<style>
div
{
background: url("Image/191203174105-edward-whitaker-1-large-169.jpg")
;
height: 300px;
width: 300px;
}
</style>
<body>
<div id="div"></div>
<button id="button">Next</button>
<script>
As here I took variable im where I feed 3 images.
var im=[
{'img':'Image/191203174105-edward-whitaker-1-large-169.jpg',}
,{'img':'Image/5718897981_10faa45ac3_b-640x624.jpg',},
{'img':'Image/gettyimages-836272842-612x612.jpg',},
];
var a=document.getElementById('button');
var b=document.getElementById('div')
a.addEventListener('click',next);
so here according to my knowledge it should provide the link of the each pic as loop starts but in program. I dont get the desired result. Can you please help me understand why this is happening?
function next()
{
for(var i=1;i<im.length;i++)
{
b.style.background=`url(${im[i].img})`;
}
}
</script>
</body>
</html>
var i = 0;
var im = [{
'img': 'https://picsum.photos/536/354'
},
{
'img': 'https://picsum.photos/id/237/536/354'
},
{
'img': 'https://picsum.photos/seed/picsum/536/354'
}
];
var a = document.getElementById('button');
var b = document.getElementById('div')
a.addEventListener('click', next);
function next() {
console.log(i);
b.style.background = `url(${im[i].img})`;
i++;
if (i == im.length) {
i = 0;
}
}
div {
background: url("https://picsum.photos/id/1084/536/354?grayscale");
height: 300px;
width: 300px;
}
<div id="div"></div>
<button id="button">Next</button>
If you're looking to cycle through pictures on a button click, then you can't really use a loop. In the code that you posted, on the click of the button, it rapidly looped through all of the pictures. You need to create a counter, and increment it on each button click.
The snippet below I've added in a previous button as well and you can cycle through the pictures both forward and backward.
const im = {
'img1': 'https://placehold.it/300x150/ff0000/ffffff?text=image_1',
'img2': 'https://placehold.it/300x150/00ff00/ffffff?text=image_2',
'img3': 'https://placehold.it/300x150/0000ff/ffffff?text=image_3',
};
const imgDiv = document.getElementById('imgDiv')
const btnNext = document.getElementById('btnNext');
const btnPrev = document.getElementById('btnPrev');
const totImages = Object.keys(im).length;
let imgNumber = 1;
btnNext.addEventListener('click', next);
btnPrev.addEventListener('click', prev);
function next() {
imgNumber++
let img = imgNumber <= totImages ? `img${imgNumber}` : null;
if (img) imgDiv.style.background = `url(${im[img]})`;
if (imgNumber === totImages) btnNext.disabled = true;
if (imgNumber > 1) btnPrev.disabled = false;
}
function prev() {
imgNumber--
let img = imgNumber >= 0 ? `img${imgNumber}` : null;
if (img) imgDiv.style.background = `url(${im[img]})`;
if (imgNumber < totImages) btnNext.disabled = false;
if (imgNumber === 1) btnPrev.disabled = true;
}
#imgDiv {
background: url("https://placehold.it/300x150/ff0000/ffffff?text=image_1");
height: 150px;
width: 300px;
}
#btnDiv {
width: 300px;
height: auto;
position: relative;
}
#btnPrev {
position: absolute;
left: 0;
top: 0;
}
#btnNext {
position: absolute;
right: 0;
top: 0;
}
<div id="imgDiv"></div>
<div id='btnDiv'>
<button id="btnPrev" disabled>&loarr; Prev</button>
<button id="btnNext">Next &roarr;</button>
</div>

Trying to click div and fire off function in a class everytime it is clicked...says TypeError in console

I have been looking at how to use classes to create objects in Javascript and wanted to create a class with a function inside that I could use once a div is clicked...However, every time I click the div I get TypeError
I have google search answers and see results with a button in html solution, but I want to do this using javascript only.
I have tried using
document.getElementById("myDiv").onclick = function(event) {Bucket.selectAndFill(event)};
but it says that selectAndFill is not a function in the console.
let buckets = [];
class Bucket {
constructor(Content, SelectStatus) {
this.content = Content;
this.selectStatus = SelectStatus;
}
selectAndFill() {
for (let bucket of buckets) {
this.content = "i changed it";
}
}
}
for (let i = 0; i < 4; i++) {
buckets[i] = new Bucket("empty", false);
console.log(buckets[i]);
}
//this line was my attempt but it says that selectAndFill is not a function in the console
document.getElementById("myDiv").onclick = function() {
Bucket.selectAndFill()
};
#myDiv {
position: relative;
width: 100px;
height: 100px;
background: red;
}
<div id="myDiv">
</div>
You can call the function from Class modifying the call this way:
const bucketFill = new Bucket;
document.getElementById("myDiv").onclick = bucketFill.selectAndFill;
Just add static keyword next to the method.
let buckets = [];
class Bucket {
constructor(Content, SelectStatus) {
this.content = Content;
this.selectStatus = SelectStatus;
}
static selectAndFill() {
for (let bucket of buckets) {
this.content = "i changed it";
}
console.log(buckets);
}
}
for (let i = 0; i < 4; i++) {
buckets[i] = new Bucket("empty", false);
console.log(buckets[i]);
}
document.getElementById("myDiv").onclick = function() {
Bucket.selectAndFill();
};
#myDiv {
position: relative;
width: 100px;
height: 100px;
background: red;
}
<div id="myDiv">
</div>

Make appear text in Javascript

I'm trying to make appear text in Javascript.
That's my code :
HTML :
<div id="t1">Ecologie</div>
<div id="t2">Planète</div>
<div id="t3">BIO</div>
<div id="t4">Responsable</div>
<div id="t5">Changement</div>
<div id="t6">Durable</div>
<script type="text/javascript">var mytimeout = setTimeout(DisplayElem(), 2000)
</script>
CSS :
#t1
{
position: absolute;
color: green;
font-size: 50px;
top: 50%;
left: 13%;
display: none;
}
#t2
{
position: absolute;
color: green;
font-size: 60px;
top: 40%;
left: 70%;
display: none;
}
and Javascript :
function Display (elem) {
elem.style.display = block;
}
var compteur = 0;
function DisplayElem()
{
compteur += 1;
var id = 't' + compteur;
elem = document.getElementById(id);
Display(elem);
mytimeout = setTimeout(DisplayElem(), 2000)
if(compteur == 6)
{
window.clearTimeout(mytimeout);
}
}
I got this error : Uncaught ReferenceError: block is not defined
on my line :elem.style.display = block;
When i open my page i want all of my div invisible. But after a few second i would like to have on who appear, and the next one, and the next one...
Thank you
Here is your complete working code:
var compteur = 1;
function Display (elem) {
elem.style.display = 'block';
}
function DisplayElem()
{
var id = 't' + compteur;
elem = document.getElementById(id);
Display(elem);
compteur += 1;
if (compteur <= 6)
setTimeout(DisplayElem, 2000);
}
DisplayElem();
See the DEMO here
You have forgotten the delimiters around the string block:
function Display (elem) {
elem.style.display = 'block';
}
Side note: Instead of setting the timeout the last time and then removing it, just skip setting it:
if (compteur < 6) {
mytimeout = setTimeout(DisplayElem(), 2000)
}

Categories