Create a new DOM with unique id based on the latest array - javascript

I want to create a new div element, with unique id from the latest array that i push every i click a create button , but it seem my code not working, here is my code below :
$(document).ready(function(){
var arr = [];
counter = 0;
$('#newDiv').on('click', function(){
$('.container').append('<div class="image">hallo</div');
counter ++;
arr.push(counter);
$('.image').attr('id',arr[arr.length-1]);
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div class="container"></div>
<button id="newDiv">create new div</button>
</body>
</html>

On each click you are setting id of each image element to last element in array, instead you can do something like this.
let arr = [], counter = 0;
$('#newDiv').on('click', function() {
arr.push(counter++)
const img = $('<div />', {
'class': 'image',
'id': arr.slice(-1)
}).text('hallo');
$('.container').append(img)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
<button id="newDiv">create new div</button>
Or you can first push counter to array and then take last element for array with slice and use it as id.
let arr = [], counter = 0;
$('#newDiv').on('click', function() {
arr.push(counter++)
const img = $(`<div class="image" id=${arr.slice(-1)}>hallo</div>`)
$('.container').append(img)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
<button id="newDiv">create new div</button>

First when you use classe query selector it would add the id to every element with that class so here is a work around you can use :
Add the add on the appending part
$(document).ready(function(){
var arr = [];
counter = 0;
$('#newDiv').on('click', function(){
counter ++;
arr.push(counter);
$('.container').append('<div id='+(arr.length-1)+' class="image">hallo '+(arr.length-1)+'</div');
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div class="container"></div>
<button id="newDiv">create new div</button>
</body>
</html>

Your original code is selecting all div with the image class and updating them all with the latest number.
I suggest creating the div adding the number to the new div only and then appending it to the container.
Please review the updated code below:
$(document).ready(function() {
var arr = [];
counter = 0;
$('#newDiv').on('click', function() {
counter++;
arr.push(counter);
// Create div
$('<div class="image"></div').text('hallo')
// Add ID attribute
.attr('id', arr[arr.length - 1])
// Apend new div to container
.appendTo('.container');
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div class="container"></div>
<button id="newDiv">create new div</button>
</body>
</html>

Related

cannot change css property of desired amount of elements using eventListener due to elements being created by javascript

I am attempting to change the backgroundColor of "gridElement" once "button" is clicked.
What was attempted, changing the way the elements are created to later include the event:
cloneNode() // doesn't work with eventListeners unless you use eventDelegation, in this case there is no parentElement to delegate the event too.
jQuery.clone() // the event is not tied directly to "gridElement" rather it is tied to "button" so jQuery.clone() would not be deep copying any associated events.
Also, attempting to make references to all gridElements:
used window.globalVarRef = localVar. // only references the first element and not all.
How can I modify the code so that the eventListener will change all "gridElement" and not just the first?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="CSS/main.css">
<title> Method 1 // appendChild() </title>
</head>
<body>
<div id="container">
<div id="gridContainer"></div>
</div>
<script>
const gridContainer = document.getElementById('gridContainer');
function createPixels(){
let pixels = 256;
for(let k=0;k<pixels;k++) {
const gridElement = document.createElement('div');
gridElement.classList.add('gridElement');
gridContainer.appendChild(gridElement);
window.allGridElements = gridElement;
}
}
createPixels();
const button = document.createElement('button');
button.classList.add('button');
button.textContent = 'button';
gridContainer.appendChild(button);
function changeBkg(){
window.allGridElements.style.backgroundColor = 'blue';
}
button.addEventListener('click', changeBkg);
</script>
</body>
</html>
The problem lies in your changeBkg function. To select all of the elements with the class of "gridElement", you want to use a for loop to find those elements and then change their styles. I added some basic css to the grid element so we can see the color change in action. Does that solve your issue?
.gridElement {
width: 100px;
height: 100px;
background: red;
display: inline-block;
margin-right: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="CSS/main.css">
<title> Method 1 // appendChild() </title>
</head>
<body>
<div id="container">
<div id="gridContainer"></div>
</div>
<script>
const gridContainer = document.getElementById('gridContainer');
function createPixels(){
let pixels = 256;
for(let k=0;k<pixels;k++) {
const gridElement = document.createElement('div');
gridElement.classList.add('gridElement');
gridContainer.appendChild(gridElement);
window.allGridElements = gridElement;
}
}
createPixels();
const button = document.createElement('button');
button.classList.add('button');
button.textContent = 'button';
gridContainer.appendChild(button);
function changeBkg(){
var items = document.getElementsByClassName('gridElement');
for (let i=0; i < items.length; i++) {
items[i].style.backgroundColor = 'blue';
}
}
button.addEventListener('click', changeBkg);
</script>
</body>
</html>

Increase and Decrease of count

I'm trying to create a code that can increase and decrease via clcik of a button
html code but the problem is i cant get it to function I've tried different options.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<div id="body">
<h1>COUNTER</h1>
<span id="time">0</span><br>
<button id="lower" onclick="reduceone()" type="button">LOWER COUNT</button><BR>
<button id="add" onclick="addone()" type="button">ADD COUNT</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="index.js"></script>
</body>
</html>
javascript code:
$("#add").click(function (){
let count = 0;
count ++;
$("#time").text(count);
});
$(#lower).click(function(){
let count = 0;
count --;
$("#time").text(count)
});
Try this
let count = 0;
$("#add").click(function (){
count ++;
$("#time").text(count);
});
$(#lower).click(function(){
count --;
$("#time").text(count)
});
You have to make variable (count ) a global variable so all functions can access his value . If you put variable(count) in a function then only that function can access his value . Hope you understand
You need to share the state between two functions so each of them could see the shared state that they are changing.
Also, all id or class names should be between inverted commas like that "#lower"
let count = 0; // Shared state that both functions can see
$("#add").click(function (){
count++;
$("#time").text(count);
});
$("#lower").click(function(){ // "#lower" not #lower
count--;
$("#time").text(count)
});

Count key presses and display them in HTML

I made a simple "spacebar simulator" game with HTML and JavaScript. Every time the user presses spacebar an image is replaced with another one, and when the key is released it is reset to the original image.
I would like to add a counter to the page, which counts the number of times the user has pressed spacebar. The source code is below:
var myRealUrl = "./assets/spacebar.png";
$("body").on("keydown", function (e) {
if(e.which == 32){
$("#spacebar").attr("src", "./assets/spacebar_pressed.png")
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
var button = document.getElementById('counter'),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
<span id="counter"><p></p></span>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed</p><p id="counter">0</p><p> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>
So set up a page level variable and increment it in the keydown event handler.
Your attempt at the "button" click code didn't work because the p element that needed to be clicked had no content inside of it, so it wasn't rendering on the screen and therefore there was nothing to click on.
Also, you can't have more than one element with the same id and it's invalid to put a p inside of a span.
var counter = 0; // Variable to hold the count
var myRealUrl = "./assets/spacebar.png";
var count = document.getElementById('counter');
$("body").on("keydown", function (e) {
if(e.which == 32){
counter++; // Increment the counter
$("#spacebar").attr("src", "./assets/spacebar_pressed.png");
count.textContent = counter; // Log the count
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed <span id="counter">0</span> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>

Beginner javascript arrays

I am new to JavaScript and I am trying to do something very simple. I wan to appear array[1] text in firstDiv's innerHTML when I click button.
I have followed all instructions but still it's not working.
<!doctype html>
<html>
<head>
<title>Learning Javascript</title>
<meta charset="utf-8" />
<meta htttp-equiv="content-type" contents="text/html; charset-utf8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<button id="stylesChanger">Change the text !</button>
<div id="firstDiv">This sis some text</div>
<script type="text/javascript">
var myArray=new Array[];
myArray[0]="pizza";
myArray[1]="chocolate";
document.getElementById("stylesChanger").onclick=function(){
document.getElementById("firstDiv").innerHTML=myArray[1];
}
</script
</body>
</html>
change your var myArray=new Array[]; to var myArray=[];
Then it will work
var myArray=[];
myArray[0]="pizza";
myArray[1]="chocolate";
document.getElementById("stylesChanger").onclick=function(){
document.getElementById("firstDiv").innerHTML=myArray[1];
}
<button id="stylesChanger">Change the text !</button>
<div id="firstDiv">This sis some text</div>
This code will make sure you get the first element of myArray on button click. And sets the div text as myArray first element.
Working Sample: JSFIDDLE
var myArray = new Array();
myArray[0] = 'pizza';
myArray[1] = 'chocolate';
var btn = document.getElementById('stylesChanger');
btn.addEventListener('click', getArrayFirstElement, false);
function getArrayFirstElement(){
document.getElementById("firstDiv").innerHTML = myArray[0];
}

Creating tabs with listviews dynamically in jQuery mobile

I am trying to create tabs with listviews in JQM dynamically on a button click. Currently, I use JS array that contains sample data which will finally be populated via ajax. After research, it seems that I should trigger either trigger("create") or trigger ("refresh"), but apparently, I don't do it correctly. Here's the code:
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>navbar demo</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script>
<script type="text/javascript" src="../JS/nav.js"></script>
</head>
<body>
<button onclick="fillCategories()">Fill</button>
<div id = "decisions" > </div>
</body>
</html>
Javascript:
function fillCategories() {
var navElements = [{"category_sublist_id":"1","category_sublist_name":"Europe"},
{"category_sublist_id":"2","category_sublist_name":"Asia"},
{"category_sublist_id":"3","category_sublist_name":"Americas"}];
var categoriesTabs = $('<div id="categories">')
.attr("data-role","tabs")
.appendTo("#decisions");
var navBar = $("<div>").attr("id","categoriesNames")
.attr("data-role","navbar")
.appendTo("#categories");
var listElements = [{"sublist_row_id":"1","category_sublist_id":"1","sublist_name":"Great Britain"},
{"sublist_row_id":"2","category_sublist_id":"1","sublist_name":"Sweden"},
{"sublist_row_id":"3","category_sublist_id":"1","sublist_name":"France"},
{"sublist_row_id":"4","category_sublist_id":"1","sublist_name":"Germany"}];
$("#categoriesNames").append($("<ul>").attr("id","categoriesUl"));
$(navElements).each(function(){
$("#categoriesUl").append($("<li>")
.attr("value", this.category_sublist_id)
.append($("<a>")
.attr("href", "#sublist"+this.category_sublist_id)
.attr("data-theme","a")
.attr("data-ajax","false")
.text(this.category_sublist_name)));
});
$("#categories").append(navBar).trigger("create");
categorySublistView("categories", "sublist2", listElements);}
function categorySublistView(elementId, listLink, listData) {
var listId = listLink+"id";
var tab = $("<div>").attr("id",listLink)
.addClass("ui-content")
.appendTo("#"+elementId);
var list = $("<ul>").attr("data-role","listview")
.attr("data-inset","true")
.attr("data-icon","false")
.attr("id", listId)
.appendTo("#"+listLink);
$(listData).each(function(){
var li = $("<li/>")
.attr("value",this.sublist_row_id)
.appendTo("#"+listId);
var link =$("<a>")
.attr("href", "#")
.text(this.sublist_name)
.appendTo(li);
});
if ( $('#'+listId).hasClass('ui-listview')) {
$('#'+listId).listview('refresh');
}
else {
$('#'+listId).trigger('create');
}}
edit:
My initial intention was to draw 3 tabs in the navbar which are listviews, which are visible on tab clicks

Categories