hide button at end of array - javascript

so here is the code i have so far, now i want to remove the button whenever the color is at the end of the array but i dont get it to work i tried different things with an if statement like this:
if(color.length){
document.getElementById("button").remove();
}
and with "removechild" but none of these works does anyone have an solution?
var color = ["green", "red", "black"];
function page() {
document.body.style.backgroundColor = "grey";
//style page
createButtons(10);
}
page();
function onbuttonclicked(a) {
var Amount = document.getElementById("button" + a);
var click = Amount.getAttribute('Color');
var change = color.indexOf(click);
Amount.setAttribute('style', 'background-color:' + color[change + 1]);
Amount.setAttribute('Color', color[change + 1]);
if(color.length){
document.getElementById("button").remove();
}
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function createButtons(amount) {
for (var a = 1; a <(amount + 1); a++) {
var button = document.createElement("button");
button.id = "button" + a;
button.innerHTML = "button " + a;
button.setAttribute('Color', color[0]);
button.setAttribute('style', 'background-color:' + color[0]);
container.appendChild(button);
}
set_onclick(amount);
}
so for example i have a few green buttons when you click on the buttons the color changes a few times, the last color is black if the button is black and you click on it then i want to hide the buttons so you dont see it anymore

In order to check if the background color is the same as the last color, simply compare the elements (you named it Amount) background color with the last element in the array. And you also have to put the if statement BEFORE changing the color.
if (Amount.style.backgroundColor == color[color.length-1]) {
Amount.remove();
However you should re-think about your naming since it can get a little confusing.
For example: Amount is definetly the wrong name since it refers to the clicked element. The parameter you pass (a) is the amount.
If you have any questions feel free to ask them.
let color = ["green", "red", "purple", "blue", "black"];
function page() {
document.body.style.backgroundColor = "grey";
//style page
createButtons(30);
}
page();
function onbuttonclicked(a) {
var Amount = document.getElementById("button" + a);
var click = Amount.getAttribute('Color');
var change = color.indexOf(click);
if (Amount.style.backgroundColor == color[color.length - 1]) {
Amount.remove();
} else {
Amount.setAttribute('style', 'background-color:' + color[change + 1]);
Amount.setAttribute('Color', color[change + 1]);
}
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function createButtons(amount) {
for (var a = 1; a < (amount + 1); a++) {
var button = document.createElement("button");
button.id = "button" + a;
button.innerHTML = "button " + a;
button.setAttribute('Color', color[0]);
button.setAttribute('style', 'background-color:' + color[0]);
document.getElementById("container").appendChild(button);
}
set_onclick(amount);
}
<div id="container">
</div>

Related

AddEventListener running twice

I'm writing a simply game in javascript, which consists of colored squares and you have to choose the square with the rgb displayed in the screen.
What happens is that when I click in a square, and then I click play again to get a new color, addEventListener runs twice, the first time it says that the answer is equals the previous rgb value, the second time it says the answer is equals the new rgb value. The problem is that entering with the wrong answer, makes you points = 0 even though you got it right.
Any suggests what might be happening?
That's my code:
window.onload = function() {
var buttonNewColor = document.getElementById("buttonNewColor");
var squares = document.querySelectorAll(".square");
buttonNewColor.onclick = getColors;
}
function getColors() {
answer = colors[getRandomInt(6) - 1];
colorChoice.innerHTML = answer;
console.log("answer top: " + answer);
for (var i = 0; i < squares.length; i ++) {
squares[i].style.backgroundColor = colors[i];
squares[i].addEventListener("click", function(){
console.log("Square Clicked");
clickedColor = this.style.backgroundColor;
console.log("clickedColor: " + clickedColor);
console.log("answer: " + answer);
if (clickedColor === answer) {
console.log("points: " + points);
message.textContent = "Correct";
buttonNewColor.textContent = "Play Again";
points = points + 1;
score.innerHTML = "Score: " + points;
changeColors(answer);
answer = " ";
} else {
console.log("Entering on else")
points = 0;
score.textContent = "Score: " + points;
message.textContent = "Try Again";
}
});
}
}

Looping in a list and setting colors on items according the length of the items is not working

I have a problem, my code should check the length of items in my list and set color, if the item is longer than 6, color on that item should be red else blue but it returns all items red.
function onS() {
var item = "";
var itemLength = 0;
var Enum = listItems.getEnumerator();
while (Enum.moveNext()) {
var currentItem = Enum.get_current();
item += "<br/>" + currentItem.get_item("Title");
if (item.length > itemLength) {
itemLength = item.length;
if (itemLength > 6) {
document.getElementById("items").style.color = "red";
}
else
{
document.getElementById("items").style.color = "blue";
}
}
$("#items").html(item);
}
}
with
var itemLength = 0;
while ... {
if (item.length > itemLength) {
itemLength = item.length;
You say that you will enter the loop only if the current item is longer than the prévious one. So if your first item has the max length, you will never enter the loop for any other item.
Also you wrote
document.getElementById("items").style.color = "red";
That means that you have only one element with id="items" because ids have to be uniques. So it doesn't make sense to change one color so many times. You probably want to do :
$(item).style.color = "red";
You seem to be missing some code which makes this annoying to test. I think the issue is regarding this though:
item += "<br/>" + currentItem.get_item("Title");
Are you sure that currentItem.get_item("Title").length + "".length isn't always > 6?
You could change it to only look at currentItem.get_item("Title").length
document.getElementById("items") set the text color of all children of the DOM node with the id "items".
I think you want to successively only specify the color of the DOM node designed by the item variable.
You need to put this item in a separate node, e.g. a span, then set the style color of this node. This obviously impact the length you are measuring. But I feel like what you are actually trying to look at is the length of your item's title and not the length of the whole html code of items like you are doing here.
var items = $("#items");
var itemLength = 0;
while (Enum.moveNext()) {
var currentItem = Enum.get_current();
var title = currentItem.get_item("Title");
var currentItemNode = $("<span>" + title + "</span>");
items.append("<br/>");
items.append(currentItemNode);
if (title.length > itemLength) {
itemLength = item.length;
if (itemLength > 6) {
currentItemNode.css("color", "red");
} else {
currentItemNode.css("color", "blue");
}
}
}
I've fixed. Thanks for any help!
function onS() {
var item = "";
var item1 = "";
var Enum = listItems.getEnumerator();
while (Enum.moveNext()) {
var currentItem = Enum.get_current();
if(currentItem.get_item("Title").length>6){
document.getElementById("items").style.color = "red";
item += "<br/>" + currentItem.get_item("Title");
}
else {
document.getElementById("items1").style.color = "blue";
item1 += "<br/>" + currentItem.get_item("Title");
}
}
$("#items").html(item);
$("#items1").html(item1);

Determine radio button not selected anymore

I wrote a javascript function that change the style of a div (here a TR tag) when I select a radio button in form (called by onchange event).
function handleCheck(myRadio) {
var vak = 'vak' + myRadio.name + 'x' + myRadio.value;
var col = document.getElementById(vak);
col.style.backgroundColor = "black";
col.style.color = "white";
}
However, often when you select option X another option is deselected while you can select only one value at the time in the same. This option is not triggered by the onchange event. Is there a way to determine that a radio button is not checked any more?
You will have to clear previously assigned classes. Take a look at this example:
function handleCheck(myRadio) {
clear(myRadio.className);
var vak = 'vak' + myRadio.name + 'x' + myRadio.value;
var col = document.getElementById(vak);
col.className += ' selected';
}
function clear(className) {
var tr = document.querySelectorAll('tr.vak' + className);
for (var i = 0; i < tr.length; i++) {
tr[i].className = 'vak' + className;
}
}
Demo: http://jsfiddle.net/abh7guv5/
If I understood correctly what you are trying to achieve, simply read document.getElementById("myRadio").checked - it will be true or false
well, if I understand you correctly, you have a function that applies some styles whenever you check a radio button, but you also would like to remove styles from elements, that corresponds to already unchecked buttons. If yes, you can store your previous checked item in a variable, then you might want something like:
var previousElement = null;
function handleCheck(myRadio) {
var vak = 'vak' + myRadio.name + 'x' + myRadio.value;
var col = document.getElementById(vak);
col.style.backgroundColor = "black";
col.style.color = "white";
if(previousElement!==null&&previousElement!==col){
previousElement.style.color = ""; // or whatever you want
}
previousElement = col;
}

Javascript to create multiple div elements onclick

I need help with this app. I want the user to choose a name, color and number. When the form is submitted, boxes of the chosen color and number are generated. More boxes can be added and the originals are not erased. Each box has random positioning and a unique id.
Here is my effort: http://jsfiddle.net/christopherpl/gnVj6/
//Invoke functions only after page has fully loaded
window.onload = init;
//Create an array that will be populated by the user generated boxes
var boxes = [];
//Create a global counter variable that keeps track of the number of
//boxes generated
var counter = 0;
//Create a Box constructor function with parameters, to create box objects
//for each box that's generated
function Box(id, name, color, x, y) {
this.id = id;
this.name = name;
this.color = color;
this.x = x;
this.y = y;
}
//Set up the onclick event handler for the generate button input
function init() {
var generateButton = document.getElementById("generateButton");
generateButton.onclick = generate;
var clearButton = document.getElementById("clearButton");
clearButton.onclick = clear;
}
//Get boxes' name from user
function generate() {
var data = document.forms.data;
var textInput = document.getElementById("name");
var name = textInput.value;
if (name == null || name == "") {
alert("Please give your Amazing Box a name");
return;
}
//Get color option from user
var colorSelect = document.getElementById("color");
var colorOption = colorSelect.options[colorSelect.selectedIndex];
var color = colorOption.value;
if (!color) {
alert("Pick a color");
return;
}
//Get number of boxes to be generated from user
var amountArray = data.elements.amount;
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
//Create and append the new <div> element
var div = document.createElement("div");
//Randomly position each <div> element
var x = Math.floor(Math.random() * (scene.offsetWidth-101));
var y = Math.floor(Math.random() * (scene.offsetHeight-101));
//Give each <div> element a unique id
var newId = div;
newId = counter++;
id = newId;
//Add the style, including the background color selected
//by the user.
div.style.left = x + "px";
div.style.top = y + "px";
div.style.backgroundColor = color;
div.setAttribute("class", "box");
scene.appendChild(div);
div.innerHTML = "Box of " + name + "<br />(click me)";
//Create an onclick event displaying the
//details of each box generated
div.onclick = function() {
alert("You clicked on a box with id " + id +
", named Box of " + name + ", whose color is " + color +
" at position " + div.style.top + ", " + div.style.left)
}
//Form reset
data = document.getElementById("data");
data.reset();
}
}
}
//Clear the boxes from scene div
function clear() {
var sceneDivs = document.querySelectorAll("div#scene div");
for (var i = 0; i < sceneDivs.length; i++) {
var scene = document.getElementById("scene");
var cutList = document.getElementsByTagName("div")[1];
scene.removeChild(cutList);
}
}
In your code, when you do this loop:
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
/* make the div */
}
}
You are always just making one box. What you need to do is a second loop, using the value of the radio button as the length of the loop. Something like:
var totalBoxes = 0;
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
totalBoxes = amountArray[i].value;
}
}
for (i = 0; i < totalBoxes; i++) {
/* make the div */
}
That way you will get 5 boxes if the user checked the 5 box, and so on.

" document.getElementById onmouseover and function " does not behave as wished × 108641

In this function, it should give the menu items (li's) an specific background (png) out of an array. However; it doesn't. It gives all the li's the background called color 'blue' :(.
Do you see the problem?
//Gives the menu items a style when hovering over it, in the sequence of the setting in the variable 'backgrounds', on top.
var backgrounds = ["blue", "green", "pink", "purple"];
function MenuColorChange() {
for (var i = 0; i <= 10 ; i++) {
document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseover = function() {
this.style.backgroundImage= "url(images/" + backgrounds[(i % backgrounds.length)] + ".png)";
}
document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseout = function() {
this.style.background = 'none';
MenuActiveColor();
}
}
}
Html:
<ul>
<li id="custom-menu-item-id-1">
<a href="#">
Home
</a>
</li>
/* And 3 li's more... */
</ul>
The function you use for onmouseover is a closuse of the outer function, in the time it is executed all onmouseover handlers have the save value of i, to achieve what you seen to want do:
//Gives the menu items a style when hovering over it, in the sequence of the setting in the variable 'backgrounds', on top.
var backgrounds = ["blue", "green", "pink", "purple"];
function MenuColorChange() {
for (var i = 0; i <= 10 ; i++) {
document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseover = (function(valueOfI){ return function() {
this.style.backgroundImage= "url(images/" + backgrounds[(valueOfI % backgrounds.length)] + ".png)";
}; })(i);
document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseout = function() {
this.style.background = 'none';
MenuActiveColor();
}
}
}
This surprises me. I would expect it to make all the backgrounds pink. The reason this happens is because by the time you actually hover over any of your <li> elements, i will be 10, and 10 % 4 = 2. Index #2 of your array is 'pink'.
To ensure that i is the value you want when the mouseover and mouseout events are fired, wrap them in a function.
function MenuColorChange() {
for (var i = 0; i <= 10 ; i++) {
(function(i) {
document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseover = function() {
this.style.backgroundImage = "url(images/" + backgrounds[(i % backgrounds.length)] + ".png)";
}
document.getElementById("custom-menu-item-id-" + (i + 1)).onmouseout = function() {
this.style.background = 'none';
MenuActiveColor();
}
}(i));
}
}
Here is an explanation that may help: variables-in-anonymous-functions

Categories