Display different text values in an array with a button - javascript

Currently all values in the array are displayed at once when clicking on one of the two buttons. My goal is that the first value is displayed by default and with next/previous the next/previous array entry is displayed.
How can I realize realize this simply?
var array = ["text1", "text2", "text3"];
function next(){
//Next text in Array
document.getElementById('text').innerHTML = array.join('<br />');
}
function prev(){
//Previous text in Array
document.getElementById('text').innerHTML = array.join('<br />');
}
<div id="siggen">
<div style="background-color: orange; height: 150px; width: 300px" id="content">
<p id="text"></p>
</div>
<button id="btnPrev" onclick="prev()">Previous</button>
<button id="btnNext" onclick="next()">Next</button>
</div>
Follow up Question
I looked at the link below from the answer. I have now added new datas to my array and would like to output the id in the left column and the name in the right column of my div.
The name is output correctly in the right column. But the id is not displayed but undefined is displayed. What is the reason for this?
The default values do not work yet either.
const arr = [{_id:1,name:"T-Rex"},{_id:3,name:"Predator X"},{_id:4 ,name:"Velociraptor"},{_id: 6, name:"Triceratops"}]
let currentIndex = 1;
let currentName = arr[0].name;
// initial log
log(currentId)
log(currentName);
function next(){
move();
}
function previous(){
move(false);
}
function move(advance = true){
currentIndex = (currentIndex + (advance ? 1 : -1) + arr.length) % arr.length;
currentName = arr[currentIndex].name;
currentId = arr[currentIndex].id;
log();
}
function log(){
document.getElementById('text').innerHTML = currentName;
document.getElementById('id').innerHTML = currentId;
}
<div style="background-color: orange; height: 300px; width: 500px" id="content">
<div style="background-color: green; height: 100%; width: 250px; float: left">
<p id="id"></p>
</div>
<div style="background-color: lightblue; height: 100%; width: 250px; float: right">
<p id="text"></p>
</div>
</div>
<button onclick="previous();">Previous</button>
<button onclick="next();">Next</button>

Follow up answer:
const arr = [{_id:1,name:"T-Rex"},{_id:3,name:"Predator X"},{_id:4 ,name:"Velociraptor"},{_id: 6, name:"Triceratops"}]
let currentIndex = 1;
let currentId = arr[0]._id;
let currentName = arr[0].name;
// initial log
log(currentId, currentName)
function next(){
move();
}
function previous(){
move(false);
}
function move(advance = true){
currentIndex = (currentIndex + (advance ? 1 : -1) + arr.length) % arr.length;
currentName = arr[currentIndex].name;
currentId = arr[currentIndex]._id;
log(currentId, currentName);
}
function log(currentId, currentName){
document.getElementById('id').innerHTML = currentId;
document.getElementById('text').innerHTML = currentName;
}
<div style="background-color: orange; height: 300px; width: 500px" id="content">
<div style="background-color: green; height: 100%; width: 250px; float: left">
<p id="id"></p>
</div>
<div style="background-color: lightblue; height: 100%; width: 250px; float: right">
<p id="text"></p>
</div>
</div>
<button onclick="previous();">Previous</button>
<button onclick="next();">Next</button>

Something like this?
var array = ["text1", "text2", "text3"];
let currentIndex = 0;
let currentId = array[0];
log(currentId);
function next(){
move();
}
function previous(){
move(false);
}
function move(advance = true){
currentIndex = (currentIndex + (advance ? 1 : -1) + array.length) % array.length;
currentId = array[currentIndex];
log(currentId);
}
function log(currentId){
document.getElementById('text').innerHTML = currentId;
}
<p id="text"></p>
<button onclick="next();">Next</button>
<button onclick="previous();">Previous</button>
Also, I got the code from this question, I only changed the code to make it display the text on the tag p

Related

How to use the Spacebar for changing color in JS [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
i have a question about JS
i just want when i write for example Own(the 'Own' word is in the array) in the input feild and then i press spacebar the color of Own word in head gets green and when i write for example
'false' the color of the Own word in the head gets red
and i want this for the rest of them i Hope you Guys Find out what i'm saying
thanks..
var seconds = 60;
var timer;
function myFunction() {
if(seconds < 60) {
document.getElementById("timer").innerHTML = seconds;
}
if (seconds >0 ) {
seconds--;
} else {
clearInterval(timer);
}
}
document.getElementById("No1").onkeypress = function() {
if(!timer) {
timer = window.setInterval(function() {
myFunction();
}, 1000);
}
}
document.getElementById("timer").innerHTML="1:00";
var text = ["Own","food","need","turn","you"]
var i;
document.getElementById('Text').innerHTML +='';
for(i = 0; i < text.length; i++){
document.getElementById('Text').innerHTML += text[i]+" ";
}
const words = [];
const memorizer = (ev) => {
const inp = ev.target;
const val = inp.value.trim();
if(ev.key === ' ') {
const valSpl = val.split(' ');
words.push(valSpl[0]);
inp.value = valSpl[1] || '';
}
if(ev.key === ' ' && val === '' ) {
inp.value = words.length ? words.pop() : '';
}
console.clear();console.log(words);
}
document.querySelector('#No1').addEventListener('keyup', memorizer);
<html>
<body style="background-color: teal !important;">
<div class="container">
<div class="row">
<div id="col" class="col-12 font-weight-bold" style="background-color: white;
font-family: 'Times New Roman', Times, serif;
text-align: center;
font-size: 30px;">
<span id="Text"></span>
</div>
<div class="col-12">
<input id="No1" type="text" class="bg-white form-control" style="width: 80% !important;
display: inline-block;
margin-top: 20px;">
<div id="timer" style=" background-color: rgb(53, 53, 53);
width: 60px;
display: inline-block;
text-align: center;
font-size: 20px;
color: white;"></div>
</div>
</div>
</div>
<script src="js/index-1.js"></script>
</body>
</html>
Change your "Text" span to a div container to put multiple span text in html file
In js file, use createElement("span") to put each text and append span to div container
when press whitespace, compare last element in words array with text array
Here is the code:
var seconds = 60;
var timer;
function myFunction() {
if (seconds < 60) {
document.getElementById("timer").innerHTML = seconds;
}
if (seconds > 0) {
seconds--;
} else {
clearInterval(timer);
}
}
document.getElementById("No1").onkeypress = function () {
if (!timer) {
timer = window.setInterval(function () {
myFunction();
}, 1000);
}
};
document.getElementById("timer").innerHTML = "1:00";
// create span to put text in Text div
var text = ["Own", "food", "need", "turn", "you"];
var i;
var textNode = document.getElementById("Text");
for (i = 0; i < text.length; i++) {
var s = document.createElement("span");
s.id = text[i];
s.innerHTML = text[i] + " ";
textNode.appendChild(s);
}
const words = [];
const memorizer = (ev) => {
const inp = ev.target;
const val = inp.value.trim();
if (ev.key === " ") {
const valSpl = val.split(" ");
words.push(valSpl[0]);
inp.value = valSpl[1] || "";
// compare the word is correct or not, and change color
if (words[words.length - 1] === text[words.length - 1]) {
document.getElementById(text[words.length - 1]).style.color = "green";
} else {
document.getElementById(text[words.length - 1]).style.color = "red";
}
}
if (ev.key === " " && val === "") {
inp.value = words.length ? words.pop() : "";
}
console.clear();
console.log(words);
};
document.querySelector("#No1").addEventListener("keyup", memorizer);
<html>
<body style="background-color: teal !important">
<div class="container">
<div class="row">
<div
id="col"
class="col-12 font-weight-bold"
style="
background-color: white;
font-family: 'Times New Roman', Times, serif;
text-align: center;
font-size: 30px;
"
>
<!-- use Text div as a container to put text span -->
<div id="Text"></div>
</div>
<div class="col-12">
<input
id="No1"
type="text"
class="bg-white form-control"
style="
width: 80% !important;
display: inline-block;
margin-top: 20px;
"
/>
<div
id="timer"
style="
background-color: rgb(53, 53, 53);
width: 60px;
display: inline-block;
text-align: center;
font-size: 20px;
color: white;
"
></div>
</div>
</div>
</div>
<script src="js/index-1.js"></script>
</body>
</html>

Why does one calculation for my onClick get applied to all elements that I'm looping through

Currently doing some exercise for CSS/Javascript animation. I'm attempting to make a Carousel slider from scratch.. I have 4 divs with 550px in width nested in a wrapper of 2200px, which is then nested in a 550px wrapper with overflow hidden.
I then created 4 LI's that I want to make clickable so that it'll translate the wrapper -550*I degrees for every LI.
I performed a queryselectorall to get all the li's, looped through it with a for loop, and created a function that should apply onclick functionality for each LI button.
The issue that I'm running into is that the first calculation of this transform property is applied to all LI's (the 550 * i for [1] [2] and [3] aren't applied).
Here's the HTML that I'm currently using.
<div id="container">
<div id="wrapper">
<div id="itemOne" >
</div>
<div id="itemTwo">
</div>
<div id="itemThree">
</div>
<div id="itemFour">
</div>
</div>
</div>
<ul>
<li class="button"></li>
<li class="button"></li>
<li class="button"></li>
<li class="button"></li>
</ul>
The Javascript
var wrapper = document.querySelector("#wrapper");
var buttons = document.querySelectorAll(".button");
for(var i = 0; i < buttons.length; i++){
var curBut = buttons[i];
curBut.addEventListener("click", function(){
wrapper.style[transformProperty] = 'translate3d(-'+((0-i) * 550) +'px,0,0'
})
console.log(((0-i) * 550));
}
console.log(buttons);
var transforms = ["transform",
"msTransform",
"webkitTransform",
"mozTransform",
"oTransform"];
var transformProperty = getSupportedPropertyName(transforms);
function getSupportedPropertyName(properties) {
for (var i = 0; i < properties.length; i++){
if(typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
If anyone could explain why the function isn't applying the different changes for the wrapper for each LI, that'd be great! Thanks!!
The global variable i is not copied into each listener, it's shared between the listeners. When you click a button, i is already set to its final value which is 4. As a possible workaround you could override the global variable with a local variable, and get the index on click using indexOf :
var wrapper = document.querySelector("#wrapper");
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
var curBut = buttons[i];
curBut.addEventListener("click", function() {
var i = Array.prototype.indexOf.call(buttons, this);
wrapper.style[transformProperty] = 'translate3d(-' + (i * 260) + 'px,0,0)';
});
}
var transforms = ["transform",
"msTransform",
"webkitTransform",
"mozTransform",
"oTransform"];
var transformProperty = getSupportedPropertyName(transforms);
function getSupportedPropertyName(properties) {
for (var i = 0; i < properties.length; i++) {
if (typeof document.body.style[properties[i]] != "undefined") {
return properties[i];
}
}
return null;
}
#container {
overflow: hidden;
background: gray;
margin-bottom: 1em;
width: 260px;
height: 100px;
}
#wrapper {
width: calc(4 * 260px);
height: 100px;
}
#wrapper div {
padding: 0 1em;
width: calc(260px - 2em);
line-height: 100px;
height: 100px;
float: left;
color: white;
font-size: 3em;
font-weight: bold;
text-align: center;
}
<div id="container">
<div id="wrapper">
<div id="itemOne">1</div>
<div id="itemTwo">2</div>
<div id="itemThree">3</div>
<div id="itemFour">4</div>
</div>
</div>
<div>
<button type="button">button 1</button>
<button type="button">button 2</button>
<button type="button">button 3</button>
<button type="button">button 4</button>
</div>

Dynamic ScrollTo function requires next element

Please have a look at my example.
I have multiple rows on my website and a scrollto() button, wich is always at the bottom of the screen.
Depending on where the usere is located on my site at a certain moment, I would like him to move to the next row after he clicked the button.
I am aware of how to make a user scrollto(), but I have no clue what kind of selector I should use.
function myFunction() {
var winScroll = window.scrollTop; // current scroll of window
// find closest div
var rows = document.querySelectorAll('.row');
var closest = rows[0]; // first section
var closest_idx = 0;
var min = closest.offsetTop - winScroll;
rows.forEach(function(row, index) {
var divTopSpace = row.offsetTop - winScroll;
if( divTopSpace < min && divTopSpace > 0 ) {
closest = row;
closest_idx = index;
min = divTopSpace;
}
});
var next_idx = closest_idx + 1;
if (next_idx == rows.length) {
next_idx = 0;
}
console.log(rows[next_idx]);
}
.rowOne {
height: 100vh;
background-color: peachpuff;
}
.rowTwo {
height: 100vh;
background-color: firebrick;
}
.rowThree {
height: 100vh;
background-color: deepskyblue;
}
.btn {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 30px;
}
<div class="main">
<div class="row rowOne">
<div class="a">
<div class="b">
Foo
</div>
</div>
</div>
<div class="row rowTwo">
<div class="a">
<div class="b">
Bar
</div>
</div>
</div>
<div class="row rowThree">
<div class="a">
<div class="b">
Foobar
</div>
</div>
</div>
<button id="btn" class="btn" onclick="myFunction()">Button</button>
</div>
Thank you in advance.
Since they are all the same height (100% of the window height), the simple solution would be to simply scroll by that amount.
window.scrollBy(0, window.innerHeight);
Otherwise, you'll need to detect which element is the "current" one, and then get it's next sibling, and then scroll to it. Something like this (haven't tested, so syntax might be off, but this should give you an idea)
var winScroll = window.scrollTop; // current scroll of window
// find closest div
var rows = document.querySelectorAll('.row');
var closest = rows[0]; // first section
var closest_idx = 0;
var min = closest.offsetTop - winScroll;
rows.forEach(function(row, index) {
var divTopSpace = row.offsetTop - winScroll;
if( divTopSpave < min && divTopSpave > 0 ) {
closest = row;
closest_idx = index;
min = divTopSpace;
}
});
var next_idx = closest_idx + 1;
if (next_idx == rows.length) {
next_idx = 0;
}
window.scrollTo(rows[next_idx].scrollTop);

Can't make 2 Player Tic Tac Toe game work JavaScript

HTML
<div class="container"> <-- div container -->
<div id="div1" onclick="canvasClicked(1);"></div>
<div id="div2" onclick="canvasClicked(2);"></div>
<div id="div3" onclick="canvasClicked(3);"></div>
<div id="div4" onclick="canvasClicked(4);"></div>
<div id="div5" onclick="canvasClicked(5);"></div>
<div id="div6" onclick="canvasClicked(6);"></div>
<div id="div7" onclick="canvasClicked(7);"></div>
<div id="div8" onclick="canvasClicked(8);"></div>
<div id="div9" onclick="canvasClicked(9);"></div>
</div> <-- div container end -->
Css
.container{ /*some css*/
border: 2px solid red;
width: 400px;
height: 400px;
margin: 0 auto;
margin-top: 10%;
}
.container div{
float: left;
height: 132px;
width: 131.3px;
border: 1px solid black;
}
JavaScript
var painted; //global variables
var content;
var winningCombinations;
var theCanvas;
var c;
var cxt;
var w;
var y;
var turn = 0;
var squaresFilled = 0; //global variables end
window.onload = function(){ //instantiating variables
painted = new Array(); //to check if the canvas contains something already
content = new Array(); //to see what the canvas contains 'X' or 'O'
winningCombinations = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],
[1,5,9],[3,5,7]]; //all possible combinations :P
for(var i=0; i<=8; i++){
painted[i] = false;
content[i]=false;
}
}
function canvasClicked(number){
theCanvas = "div" + number; //takes the div Id from html
c = document.getElementById(theCanvas);
if(painted[number-1]==false){
if(turn%2==0){ //use X here
c.innerHTML = '<img src="cross image" alt="x" width=100%
height=100%>';
content[number-1] = 'X'; //storing value in content array
}else{ // user O here
c.innerHTML = '<img src=" O image" height="100%"
width="100%" alt="O">';
content[number-1] = 'O'; //storing value in content array
}
}
else{
alert('This block is already occupied, try another block');
turn--;
squaresFilled--;
}
turn++;
painted[number-1]= true;
squaresFilled++;
checkForWinner(content[number-1]);
if(squaresFilled == 9){
alert('It is a TIE');
playAgain();
}
}
function checkForWinner(symbol){ // This functions seems to be the problem
for(var a = 0; a < winningCombinations.length; a++){
if(content[winningCombinations[a][0]]==symbol &&
content[winningCombinations[a][1]]==symbol && content[winningCombinations[a]
[2]]==symbol){
console.log(symbol + ' won!!');
}
}
}
function playAgain(){ // just another function to reset the game
y=confirm("PLAY AGAIN?");
if(y==true){
location.reload(true);
}else{
alert('Good Bye Then!!');
}
}
It runs normally but the results are not expected. It sometimes randomly make anyone winner(i guess), i can't seem to find the bug, i used debugger as well but i just can't find the problem...any help would be appreciated.
Thanks
In the function checkForWinner change:
if(content[winningCombinations[a][0]]==symbol &&
content[winningCombinations[a][1]]==symbol &&
content[winningCombinations[a][2]]==symbol){
to:
if(content[winningCombinations[a][0]-1]==symbol &&
content[winningCombinations[a][1]-1]==symbol &&
content[winningCombinations[a][2]-1]==symbol){
It would make things easier if you numbered everything from 0 instead of 1. Then you don't need all those -1.
Check your indices.
Either content[0-8] or content[1-9]
winningCombination uses 1-9
but canvasClicked uses 0-8
That's why you getting some strange results
I know I should help you with your code, but I decided to use parts of your code and suggest you an approach:
HTML :
<div class="turnInfo" id="turnInfo">Turn : O</div>
<div class="container">
<div id="div1" cell="1" onclick="canvasClicked(this);"></div>
<div id="div2" cell="2" onclick="canvasClicked(this);"></div>
<div id="div3" cell="3" onclick="canvasClicked(this);"></div>
<div id="div4" cell="4" onclick="canvasClicked(this);"></div>
<div id="div5" cell="5" onclick="canvasClicked(this);"></div>
<div id="div6" cell="6" onclick="canvasClicked(this);"></div>
<div id="div7" cell="7" onclick="canvasClicked(this);"></div>
<div id="div8" cell="8" onclick="canvasClicked(this);"></div>
<div id="div9" cell="9" onclick="canvasClicked(this);"></div>
</div>
CSS :
.turnInfo{
text-align:center;
font-size:40px;
font-weight:bold;
margin-top: 6%;
margin-bottom:10px;
}
.container{ /*some css*/
border: 2px solid red;
width: 400px;
height: 400px;
margin: 0 auto;
}
.container div{
float: left;
height: 102px;
width: 131.3px;
border: 1px solid black;
text-align:center;
padding-top:30px;
font-size:50px;
}
JS :
Variables
var cells = [0,0,0,0,0,0,0,0,0,0]; // make it 10 for the sake of array index
var turn = 'O'; // first turn : O
var infoDiv = document.getElementById('turnInfo');
Toggle the Trun
function toggleTurn(){
turn = turn == 'O' ? 'X' : 'O';
infoDiv.innerHTML = 'Turn : '+turn;
return turn;
}
Canvas Click Handler
function canvasClicked(cell){
var cellIndex = cell.getAttribute('cell');
if(!cells[cellIndex]){
cells[cellIndex] = toggleTurn();
cell.innerHTML = turn; // you can add image here.
checkWinner();
}
}
Check Result function
function checkWinner(){
winningCombinations = [
[1,2,3],
[4,5,6],
[7,8,9],
[1,4,7],
[2,5,8],
[3,6,9],
[1,5,9],
[3,5,7]
]; //all possible combinations :P
for(var index=0; index < winningCombinations.length;index++){
winCond = winningCombinations[index];
if(cells[winCond[0]] != 0 &&
cells[winCond[0]] == cells[winCond[1]] &&
cells[winCond[1]] == cells[winCond[2]])
{
alert(turn + ' is winner');
playAgain();
return;
}
}
var allCellsFilled = 1;
for(var index =1; index < cells.length; index++){
if(!cells[index]){
allCellsFilled = 0;
break;
}
}
if(allCellsFilled){
alert('Game is draw!');
playAgain();
}
}
New Game function
function playAgain(){ // just another function to reset the game
y=confirm("PLAY AGAIN?");
if(y==true){
location.reload(true);
}else{
alert('Good Bye Then!!');
}
}
You can see it here : https://codepen.io/FaridNaderi/pen/awROjY
Hope it helps.

How to clone, modify (increment some elements) before appending using jQuery?

I have an element that contains multiple elements inside it, what I need is to clone the element, but on every "new" element, I need to increment an element (the object number -see my script please-)
In the script I'm adding I need (every time I click on the button) to have : Hello#1 (by default it's the first one) but the first click make : Hello#2 (and keep on top Hello#1) second click = Hello#1 Hello#2 Hello#3 ... We need to keep the oldest hellos and show the first one.
var count = 1;
$(".button").click(function(){
count += 1;
num = parseInt($(".object span").text());
$(".object span").text(count);
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
});
.object{
width:100px;
height:20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
You just have to change a little:
var count = 1;
$(".button").click(function() {
count += 1;
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(count); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
and if you want to simplify this more use this:
$(".button").click(function() {
var idx = ++$('.object').length; // check for length and increment it with ++
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
div.find('span').text(idx); // <------here you have to put the count
cont.append(div);
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>
Use the following function, this is more modular and you can use it to update the count if you remove one of the elements
function updateCount() {
$(".object").each(function(i,v) {
$(this).find("span").text(i+1);
});
}
$(".button").click(function() {
num = parseInt($(".object span").text());
var cont = $(".container"),
div = cont.find(".object").eq(0).clone();
cont.append(div);
updateCount();
});
.object {
width: 100px;
height: 20px;
background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>
<div class="container">
<div class="object">
<p>
hello#<span>1</span>
</p>
</div>
</div>

Categories

Resources