Javascript navigation with array - javascript

I'm trying to make a navigation that chagnes the background of a div using the array data.
It isn't working like I would want it.
I'm trying to use if inside addEventListener with 'click' function.
var designNextBg = document.getElementById('js-nextbg');
var designBg = document.getElementById('js-designBg');
var designBgArray = [
'url(images/ipb.png)',
'url(images/ipg.png)',
'url(images/ipr.png)',
'url(images/ipw.png)',
'url(images/ipy.png)'
];
var positionBg = document.getElementById('js-positionBg');
var i = 0;
designNextBg.addEventListener('click', function(e) {
if (i = 0) {
designBg.style.backgroundImage = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else if (i = 4) {
designBg.style.backgroundImage = designBgArray[i];
i = 0;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else {
designBg.style.backgroundImage = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
};
});
<div id="js-designBg" class="design-bg">
<div class="design-navigation">
<span id="js-positionBg">01/05</span>
<p>
<a id="js-prevbg" class="angle-buttons"><i class="fa fa-angle-left"></i></a>
<a id="js-nextbg" class="angle-buttons"><i class="fa fa-angle-right"></i></a>
</p>
</div>
</div>

your code is way to complicated. I've added two ways to deal with i and keep it inside the bounds. For once, you can do this in the click-handler (currently commented out), or you can just continuously increment/decrement there and compute the actual index inside the array with a oneliner.
var designBg = document.getElementById('js-designBg');
var designBgArray = [
'url(images/ipb.png)',
'url(images/ipg.png)',
'url(images/ipr.png)',
'url(images/ipw.png)',
'url(images/ipy.png)'
];
var positionBg = document.getElementById('js-positionBg');
var i = 0;
var nextButton = document.getElementById('js-nextbg');
var prevButton = document.getElementById('js-prevbg');
nextButton.addEventListener('click', function(e) {
//if(++i === designBgArray.length) i=0;
++i;
updateView();
});
prevButton.addEventListener('click', function(e) {
//if(--i < 0) i += designBgArray.length;
--i;
updateView();
});
function lz(nr){//a simple leading zero function
return String(nr).padStart(2, 0);
}
funciton updateView(){
var len = designBgArray.length;
//get i back into the boundaries
//you could also take care of that in the click-handler
//but this way, it's all in one place
var index = i%len + (i<0? len: 0);
designBg.style.backgroundImage = designBgArray[index];
positionBg.textContent = lz(index+1) + "/" + lz(len);
}
<div id="js-designBg" class="design-bg">
<div class="design-navigation">
<span id="js-positionBg">01/05</span>
<p>
<a id="js-prevbg" class="angle-buttons"><i class="fa fa-angle-left"></i></a>
<a id="js-nextbg" class="angle-buttons"><i class="fa fa-angle-right"></i></a>
</p>
</div>
</div>

This code works for 'NEXT' button with changing background colours replace backgroundImage as per requirement
var designNextBg = document.getElementById('js-nextbg');
var designBg = document.getElementById('js-designBg');
var designBgArray = [
'red',
'green',
'blue',
'yellow',
'cyan'
]; var positionBg = document.getElementById('js-positionBg');
var i = 0;
designNextBg.addEventListener('click', function(e) {
if (i == 0) {
designBg.style.background = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else if (i == 4) {
designBg.style.background = designBgArray[i];
i = 0;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else {
designBg.style.background = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
};
});
<div id="js-designBg" class="design-bg">
<div class="design-navigation">
<span id="js-positionBg">01/05</span>
<p>
<input type ='button' value ='NEXT' id="js-nextbg" class="angle-buttons">
</p>
</div>
</div>

designNextBg.addEventListener('click', function(e) {
if (i = 0) {
designBg.style.backgroundImage = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else if (i = 4) {
designBg.style.backgroundImage = designBgArray[i];
i = 0;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
} else {
designBg.style.backgroundImage = designBgArray[i];
i = i + 1;
positionBg.innerHTML = "0" + (i + 1) + "/05";
return i;
};
});
Here, inside if you must give == or === for comparison. = means assignment operator which always returns true. So i=0 returns true and always the first condition gets passed. So it returns 1. So it changes the span to 01/05.

Taking into account your code and answer posted by Thomas I would provide a working example instead of blank screen and nonexistent background.
Introduced minor code improvements for easier reading, service logic isolation and less letters.
/**
* List of random images
* #type {Array}
*/
var designBgArray = [
'https://picsum.photos/200/300',
'https://picsum.photos/201/300',
'https://picsum.photos/202/300',
'https://picsum.photos/203/300',
'https://picsum.photos/204/300'
];
var getEl = function(id) {
return document.getElementById(id);
},
addClick = function(el, fn) {
el.addEventListener('click', fn);
},
lz = function(nr) {
return String(nr).padStart(2, 0);
};
var designBg = getEl('js-designBg'),
positionBg = getEl('js-positionBg'),
nextButton = getEl('js-nextbg'),
prevButton = getEl('js-prevbg');
var render = function() {
var len = designBgArray.length,
index = i % len + (i < 0 ? len : 0);
console.log('Rendering "i"', i);
designBg.style.backgroundImage = 'url('+designBgArray[index]+')';
positionBg.textContent = lz(index+1) + "/" + lz(len);
};
var i = 0;
render(); // Initial background set (if blank bg is not applicable)
addClick(nextButton, function(e) {
i++;
if (i === designBgArray.length + 1) {
i = 0;
}
render();
});
addClick(prevButton, function(e) {
i--;
if (i < 1) {
i = designBgArray.length;
}
render();
});
.angle-buttons, #js-positionBg {
background-color: white;
}
<div id="js-designBg" class="design-bg">
<div class="design-navigation">
<span id="js-positionBg">01/05</span>
<p>
<a id="js-prevbg" class="angle-buttons"><</a>
<a id="js-nextbg" class="angle-buttons">></a>
</p>
</div>
</div>

Related

How To Apply jQuery CSS Selector

I am trying to apply jquery selector on the div which are dynamically created from javaScript Loop
Div's are created from for loop assign class to each div
minus = textbox1 - textbox2;
var count = 0;
var a;
for (x = textbox1; x >= minus; x--) {
a = count++;
$('body').append('<div class="drag' + a + '" >' + x + '</div>');
}
now I am trying to add the css selector on these but it is not working
var colors = ["#42ae18","#eabc00","#147cc4","#FF6EB4","#ed4329","#8d33aa","#00b971","#e9681b","#a2b3d4","#0b863c","#eabc00","#7027a5","#c83131","#00a1de","#0bc1b6","#FF6EB4","#10a0b6","#FF6EB4","#eedfd3","#362819","#FFD700"];
var i = 0;
$(".drag").each(function(){
$(this).css("color",colors[i]);
if(i == colors.length-1)
{
i = 0;
}
else
{
i++;
}
});
the complete code is given below
$("#submitBtn").click(function(){
var x;
var minus;
var textbox1= new Number($("#value1").val());
var textbox2= new Number($("#value2").val());
var colors = ["#42ae18","#eabc00","#147cc4","#FF6EB4","#ed4329","#8d33aa","#00b971","#e9681b","#a2b3d4","#0b863c","#eabc00","#7027a5","#c83131","#00a1de","#0bc1b6","#FF6EB4","#10a0b6","#FF6EB4","#eedfd3","#362819","#FFD700"];
var i = 0;
$(".drag").each(function(){
$(this).css("color",colors[i]);
if(i == colors.length-1)
{
i = 0;
}
else
{
i++;
}
});
minus=textbox1-textbox2;
var count=0;
var a;
for(x=textbox1;x>=minus;x--){
a=count++;
$('body').append('<div class="drag'+a+'" >' +x+ '</div>');
}
});
You can use attribute starts with selector like following.
var colors = ["#42ae18", "#eabc00", "#147cc4", "#FF6EB4", "#ed4329", "#8d33aa", "#00b971", "#e9681b", "#a2b3d4", "#0b863c", "#eabc00", "#7027a5", "#c83131", "#00a1de", "#0bc1b6", "#FF6EB4", "#10a0b6", "#FF6EB4", "#eedfd3", "#362819", "#FFD700"];
var i = 0;
$("[class^=drag]").each(function () { //change selector here
$(this).css("color", colors[i]);
if (i == colors.length - 1) {
i = 0;
}
else {
i++;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="drag0">!!!!!</div>
<div class="drag1">!!!!!</div>
<div class="drag2">!!!!!</div>
<div class="drag3">!!!!!</div>
<div class="drag4">!!!!!</div>
<div class="drag5">!!!!!</div>
<div class="drag6">!!!!!</div>
<div class="drag7">!!!!!</div>
<div class="drag8">!!!!!</div>

Reset values Issue

Building a dice game and you get 3 rolls. Once you finish your turn i'm trying to have a "reset" button that will reset the values back to the original spot so the "next person" can play. The values reset as I expected but when I "roll" none of the functions are taking place and i'm pretty new in js so i'm not sure what the problem is.
var playerScore = document.getElementById('firstPlayerScore');
var rollButton = document.getElementById('roll_button');
var dice1 = new dice(1);
var dice2 = new dice(2);
var dice3 = new dice(3);
var dice4 = new dice(4);
var dice5 = new dice(5);
var diceArray = [dice1, dice2, dice3, dice4, dice5];
var cargo = 0;
var numOfRolls = 0;
var cargoButton = document.getElementById('cargo');
var canHaveCargo = false;
function restart(){
dice1 = new dice(1);
dice2 = new dice(2);
dice3 = new dice(3);
dice4 = new dice(4);
dice5 = new dice(5);
diceArray = [dice1, dice2, dice3, dice4, dice5];
cargo = 0;
numOfRolls = 0;
canHaveCargo = false;
addGlow();
updateDiceImageUrl();
document.getElementById("dice1").classList.remove('glowing');
document.getElementById("dice2").classList.remove('glowing');
document.getElementById("dice3").classList.remove('glowing');
document.getElementById("dice4").classList.remove('glowing');
document.getElementById("dice5").classList.remove('glowing');
}
//dice object
function dice(id){
this.id = id;
this.currentRoll = 1;
this.previousRoll = 1;
this.isSelected = false;
this.diceImageUrl = "img/dice/dice1.png";
this.roll = function(){
this.previousRoll = this.currentRoll;
this.currentRoll = getRandomRoll(1, 6);
}
}
//returns an array of all dice that are not currently selected so they can be rolled.
function getRollableDiceList(){
var tempDiceList = [];
for(var i = 0; i < diceArray.length; i++){
if(!diceArray[i].isSelected){
tempDiceList.push(diceArray[i]);
}
}
return tempDiceList;
}
// gets a random number between min and max (including min and max)
function getRandomRoll(min,max){
return Math.floor(Math.random() * (max-min + 1) + min);
}
// calls the roll function on each dice
function rollDice(rollableDiceList){
for(var i = 0; i < rollableDiceList.length; i++){
rollableDiceList[i].roll();
}
}
// updates each dice with the new url for the image that corresponds to what their current roll is
function updateDiceImageUrl(){
for(var i = 0; i < diceArray.length; i++){
var currentDice = diceArray[i];
currentDice.diceImageUrl = "http://boomersplayground.com/img/dice/dice" + currentDice.currentRoll + ".png";
//update div image with img that cooresponds to their current roll
updateDiceDivImage(currentDice);
}
}
//Displays the image that matches the roll on each dice
function updateDiceDivImage(currentDice) {
document.getElementById("dice"+currentDice.id).style.backgroundImage = "url('" + currentDice.diceImageUrl +"')";
}
// returns an array of all
function getNonSelectedDice(){
var tempArray = [];
for(var i = 0; i < diceArray.length; i++){
if(!diceArray[i].isSelected){
tempArray.push(diceArray[i]);
}
tempArray.sort(function(a, b){
return b.currentRoll - a.currentRoll;
});
}
return tempArray;
}
function getSelectedDice(){
var selectedDice = [];
for(var i = 0; i < diceArray.length; i++){
if(diceArray[i].isSelected){
selectedDice.push(diceArray[i]);
}
}
return selectedDice;
}
//boolean variables
var shipExist = false;
var captExist = false;
var crewExist = false;
//checks each dice for ship captain and crew. Auto select the first 6, 5 , 4.
function checkForShipCaptCrew(){
//array of dice that are not marked selected
var nonSelectedDice = getNonSelectedDice();
for(var i = 0; i < nonSelectedDice.length; i++){
//temp variable that represents the current dice in the list
currentDice = nonSelectedDice[i];
if (!shipExist) {
if (currentDice.currentRoll == 6) {
shipExist = true;
currentDice.isSelected = true;
}
}
if (shipExist && !captExist) {
if (currentDice.currentRoll == 5) {
captExist = true;
currentDice.isSelected = true;
}
}
if (shipExist && captExist && !crewExist) {
if (currentDice.currentRoll == 4) {
crewExist = true;
currentDice.isSelected = true;
canHaveCargo = true;
}
}
}
}
function addGlow(){
var selectedDice = getSelectedDice();
for (var i = 0; i < selectedDice.length; i++){
var addGlowDice = selectedDice[i];
var element = document.getElementById('dice' + addGlowDice.id);
element.className = element.className + " glowing";
}
}
function getCargo(){
var cargo = 0;
var moreDice = getNonSelectedDice();
if (canHaveCargo){
for(var i=0; i < moreDice.length; i++){
cargo += moreDice[i].currentRoll;
playerScore.innerHTML = 'You have got ' + cargo + ' in ' + numOfRolls + ' rolls!';
}
} else {
alert("You don't have Ship Captain and the Crew yet!");
}
}
rollButton.addEventListener('click', function(){
//generate rollable dice list
if (numOfRolls < 3) {
var rollableDiceList = getRollableDiceList();
//roll each dice
rollDice(rollableDiceList);
//update dice images
updateDiceImageUrl();
getNonSelectedDice();
// //auto select first 6, 5, 4 (in that order)
checkForShipCaptCrew();
addGlow();
// //adds a red glow to each dice that is selected
numOfRolls++;
}
});
cargoButton.addEventListener('click', getCargo);
var startButton = document.getElementById('restart');
startButton.addEventListener('click', restart);
http://boomer1204.github.io/shipCaptainCrew/
Here is a link to the live game since it's the only way I can describe the problem since I don't know what's not working. If you roll the dice a couple times the dice will get a blue border and be "saved" according to the rules. Now after you hit th restart button that doesn't happen anymore.
Thanks for the help in advance guys
Just add this to your restart()
function restart(){
...
shipExist = false;
capExist = false;
crewExist = false;
...
}
It's hard to replicate without a fiddle, but it seems that you are adding and removing the 'glowing' class using separate processes. Have you tried adding the glowing class the same way you are removing it?
element.classList.add("glowing")
See an example within a fiddle: https://jsfiddle.net/5tstf2f8/

Font Size changes according to count of word

function test(data) {
wordCount = {};
theWords = [];
allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i = i + 1) {
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
var result = "";
for (var i = 0; i < theWords.length; i = i + 1) {
result = result + " " + theWords[i];
$("theWords.eq[i]").css("fontSize", (wordCount.length + 50) + 'px');
}
return result;
}
console.log(test("MyWords"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm having troubles with the syntax of the line "$("theWords[i]......."
I realize how simple of a question this is, and not academic to the community, but I have been fumbling with this syntax for awhile and can't find any specific forum to correct my syntax error.
I am attempting to have the font size change according to the amount of times the word appears in a document.
wordCount = count of appears.
theWords = all words I would like to have the rule applied to
I manage to have something working with what you did using a bit more of jQuery to build the list of words to show. hope it helps :D.
$(document).ready(function() {
var data = $(".sometext").text();
wordCount = {}; theWords = []; allWords = data.match(/\b\w+\b/g); //get all words in the document
for (var i = 0; i < allWords.length; i++){
allWords[i] = allWords[i].toLowerCase();
var word = allWords[i];
if (word.length > 5) {
if (wordCount[word]) {
wordCount[word] = wordCount[word] + 1;
} else {
wordCount[word] = 1;
}
}
}
var theWords = Object.keys(wordCount); // all words over 5 characters
for(var i = 0; i < theWords.length; i = i + 1) {
$('<span/>', {
'text': theWords[i] + " ",
'class': theWords[i]
}).appendTo('.result');
}
for(var i = 0; i < theWords.length; i++) {
$("." + theWords[i]).css("font-size", 15 + wordCount[theWords[i]]*5 + "px");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="sometext">javascript is a language that could be a language without such things as language but not without things as parenthesis. language is the bigest word here.</p>
<hr>
<div class="result"></div>

I guess i need dynamic variables in javascript to do this?

I am trying to use this stopwatch here: Stopwatch Script but for many counters on the page, that are dynamically created via php loops.
For example:
<button type="button" class="btn" id="bn1" data-bid="n1">Start</button>
<br><br>
<div id=n1></div>
<br><br>
<button type="button" class="btn" id="bn2" data-bid="n2">Start</button>
<br><br>
<div id=n2></div>
Using jquery i am trying to create 2 simple functions. One to start each timer clicked and one to stop it
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<script language=javascript>
var vars = {};
var bid;
var h = 0;
var m = 0;
var s = 0;
$('[class^=btn]').on('click', function() {
var pause = $(this).text() === 'Stop';
$(this).text(pause ? 'Start' : 'Stop');
bid = $(this).attr('data-bid');
return (this.timvar ^= 1) ? startimer(bid) : stop(bid);
});
function stop(bid) {
clearTimeout(['tm' + bid]);
}
function startimer(bid) {
//vars['tm' + bid] = setInterval('disp('+bid+')',1000);
vars['tm' + bid] = setInterval(function() {
disp(bid)
}, 1000);
}
function disp(bid) {
//alert(bid);
// Format the output by adding 0 if it is single digit //
if (s < 10) {
var s1 = '0' + s;
} else {
var s1 = s;
}
if (m < 10) {
var m1 = '0' + m;
} else {
var m1 = m;
}
if (h < 10) {
var h1 = '0' + h;
} else {
var h1 = h;
}
// Display the output //
str = h1 + ':' + m1 + ':' + s1;
document.getElementById(bid).innerHTML = str;
// Calculate the stop watch //
if (s < 59) {
s = s + 1;
} else {
s = 0;
m = m + 1;
if (m == 60) {
m = 0;
h = h + 1;
} // end if m ==60
} // end if else s < 59
// end of calculation for next display
}
</script>
Somehow i have to be able to execute these 2 functions multiple times for each button, that will use a dynamic 'tm' variable that updates the text inside the n1 and n2..(etc) divs with the timer. And then when the user presses stop to be able to stop that specific tm var.
But...i am kinda lost when it comes to dynamic variables and how to properly pass them around between javascript functions...I am not even sure if there is a simpler way of doing this...I dont know what's the proper term to search for it in google. Any advice ? What am i doing wrong ?
-Thanks

how to get the image path in same way as item.src?

I am using freewall.js from http://vnjs.net/www/project/freewall/
The images would be dynamic. So html will have:
<div class="brick">
<img src="" width="100%">
</div>
JS
$(".free-wall .brick img").each(function(index, item) {
item.src = "images/" + (++index) + ".jpg";
});
The thing I want to do is to prepend a few more images to the freewall.
var temp = '<div class="brick"><img src="" width="100%"></div>';
$(".add-more").click(function() {
for (var i = 0; i < 4; ++i) {
wall.prepend(temp);
}
wall.fitWidth();
});
When the add-more button is clicked, 4 images will be prepended. the problem is how to append the image path in same way?
help appreciated!
Try
var temp = '<div class="brick"><img src="" width="100%"></div>';
$(".add-more").click(function () {
var start = $(".free-wall .brick img").length + 1;
for (var i = 0; i < 4; ++i) {
$(temp).prependTo(wall).find('img').attr('src', "images/" + (start + i) + ".jpg")
//or wall.prepend('<div class="brick"><img src="images/' + (start + i) + '.jpg" width="100%"></div>');
}
wall.fitWidth();
});
Update:
$(".add-more").click(function () {
var start = $("#freewall .brick img").length + 1,
$imgs = $(),
$img, loadcounter = 0;
for (var i = 0; i < 4; ++i) {
$img = $(temp).appendTo('.free-wall').find('img').attr('src', 'http://placehold.it/64&text=' + (start + i) + '.jpg').hide();
$imgs = $imgs.add($img);
}
$imgs.on('load error', function () {
loadcounter++;
if (loadcounter == 4) {
$imgs.show();
wall.fitWidth();
}
}).filter(function(){
return this.complete
}).trigger('load')
});
Demo: Fiddle
Try this,
$(".add-more").click(function() {
for (var i = 0; i < 4; ++i) {
src="images/"+(i+1)+".jpg";
wall.prepend('<div class="brick"><img src="'+src+'" width="100%"></div>');
}
wall.fitWidth();
});

Categories

Resources