Append div "n" times where "n" is value inside another html div - javascript

I have a div that could contain different numbers inside it and a button.
When I click on this button, I want to append divs according to the number in the div, e.g. if I have number 1 then it should append 1 div, if I have number 2 it should append 2 divs, and so on.
I also want *each appended div to have a unique id.
What I have tried so far:
$(document).ready(function() {
$('button').click(function() {
if ($(this).siblings('div').html() == '1') {
$('body').append('<div>' + 'My div' + '</div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
1
</div>
<button type="button">Add</button>

Check the following pure JavaScript approach [jsFiddle] as well as jQuery approach [jsFiddle] to append divs with unique ids based on div value:
Pure JavaScript:
var btn = document.getElementById('btn');
var val = document.getElementById('val').textContent;
var idName = 1;
function addDiv(){
var count = parseInt(val.trim());
for (var i = 0; i < count; i++) {
var appendDiv = document.createElement('div');
appendDiv.setAttribute("class", "newDiv");
appendDiv.setAttribute("id", "someId" + idName);
document.body.appendChild(appendDiv);
idName++;
}
}
btn.addEventListener('click', addDiv);
.newDiv {background-color: red; margin: 5px auto; padding: 10px;}
<div id="val">
4
</div>
<button id="btn" type="button">Add</button>
jQuery:
var idName = 1;
$("button").on("click", function(){
var count = parseInt($("#val").text().trim());
for(let i=0; i < count; i++){
$('body').append('<div class="newDiv" id="newDiv' + idName + '"></div>');
idName++;
}
})
.newDiv {
background-color: red;
margin: 5px auto;
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="val">
4
</div>
<button id="btn" type="button">Add</button>

I think something like this could work for you:
<script>
$(document).ready(function() {
$('button').click(function() {
var val = parseInt($(this).siblings('div').text().trim());
for(let i=0; i < val; i++){
$('body').append('<div>'+'TEST'+'</div>');
}
});
});
</script>

You need to remove the white space that precedes or follows the element's content and you do that with .trim().
You also need to be looking at only the previous sibling, not all the siblings because after you add one more div, it won't contain the number that the previous one does and the code will never find a match after that.
Lastly, you should use .text(), not .html() when you are looking at the text content of an element and not its HTML child content.
$(document).ready(function() {
// This is only added to demonstrate that the following
// code works no matter what the number is in the div
let val = prompt("Pick a number");
$("div")[0].textContent = " " + val + " ";
// *****************************************************
let div = $('button').prev(); // Get a reference to the <div> just prior to the button
let num = +div.text().trim(); // Get the text content of that <div> and convert to number
$('button').click(function() {
// Loop the amount of times as was in the <div>
for(var i = 0; i < num; i++) {
// Create a new <div> with an id of the current loop index
$('body').append('<div id=' + i + '>' + 'My div' + '</div>');
}
// Show newly created code (scroll to bottom of results to see)
console.log($("body").html());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
</div>
<button type="button">Add</button>

Related

need to display each character with different color

need to display each character with different color.
var str="hello"
console.log(str);
var strToArr=str.split("");
console.log(strToArr);
var letter=["red","blue","green"];
var i=0;
var reference=document.getElementById("display");
var interval=setInterval(function(){
if(i<strToArr.length){
reference.innerHTML+=strToArr[i];
reference.style.color=letter[i];
i++;}
},2000);
<body>
<span id="display"></span>
</body>
need to display each character with different color.
Using span element for each character
Note: clearInterval() clears a timer set with the setInterval() method
var str = "hello"
console.log(str);
var strToArr = str.split("");
console.log(strToArr);
var letter = ["red", "blue", "green"];
var i = 0;
var reference = document.getElementById("display");
var interval = setInterval(function() {
if (i == strToArr.length) {
clearInterval(interval)
return
}
let span = document.createElement('span')
span.style.color = letter[i]
span.innerHTML = strToArr[i]
reference.appendChild(span);
i++;
}, 500);
<span id="display"></span>
Something like this should solve your problem. Added <span> element with style and respective color. I added also two more colors.
var str="hello"
console.log(str);
var strToArr=str.split("");
console.log(strToArr);
var letter=["red","blue","green","orange","yellow"];
var i=0;
var reference=document.getElementById("display");
var interval=setInterval(function(){
if(i<strToArr.length){
reference.innerHTML+='<span style="color:' + letter[i] + ';">' + strToArr[i] + '</span>';
i++;}
},2000);
<body>
<span id="display"></span>
</body>
So the resulting DOM should look like this.
<body>
<span id="display">
<span style="color:red;">h</span>
<span style="color:blue;">e</span>
<span style="color:green;">l</span>
<span style="color:orange;">l</span>
<span style="color:yellow;">o</span>
</span>
</body>
Edit: Another probably better approach might be to don't set color at all with JS. I would prefer the :nth-child selector. Please review the documentation on the Mozilla homepage on how you can use it. E.g.:
#display > span:nth-child(0) { color: red; }
#display > span:nth-child(1) { color: blue; }
#display > span:nth-child(2) { color: green; }
#display > span:nth-child(3) { color: orange; }
#display > span:nth-child(4) { color: yellow; }
You must enclose each character with span tag so you can style each one individually. i have added a colorCounter reset, so it will loop back to red regardless how long your string is.
var str="hello this is a long string"
console.log(str);
var strToArr=str.split("");
console.log(strToArr);
var letter=["red","blue","green"];
var i=0;
var colorCounter = 0;
var reference=document.getElementById("display");
var interval=setInterval(function(){
if(i<strToArr.length){
reference.innerHTML+='<span style="color:'+letter[colorCounter]+'">'+strToArr[i]+'</span>';
i++;
colorCounter++;
// resets color counter and loop back to red
if(colorCounter > (letter.length-1)){colorCounter =0}
}
},2000);
<div id="display"></div>

Click not registering

I've added a bunch of buttons using Jquery, all of them in the same class, and I'm trying to have them do something when clicked. I have a simple on click function for them right now that just logs the word "clicked" to the console, but it is not registering any of my clicks. Here is my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Minesweeper</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="dimensions">
Width: <input type="Width" id="width"><br/>
Height: <input type="Height" id="height"><br/>
<button type="button" id="new-game" onclick="newGame()">Create</button>
</div>
<div id="board"></div>
</body>
</html>
Javascript:
function newGame() {
var cols = $("#width").val();
var rows = $("#height").val();
if (cols < 8 || rows < 8) {
return;
}else if (cols > 40 || rows > 30) {
return;
}
boardClear();
possibleBombs = (rows * cols) - 1;
numBombs = 0;
for (i = 1; i <= rows; i++) {
for (j = 1; j <= cols; j++) {
if (numBombs < possibleBombs) {
q = Math.floor(Math.random() * 2);
if (q == 0) {
numBombs += 1;
}
$("#board").append('<button type="button" class="tile" data-row = ' + i + 'data-col = ' + j + 'data-contains = ' + q + '></button>');
}
else {
$("#board").append('<button type="button" class="tile" data-row = ' + i + 'data-col = ' + j + 'data-contains = 1 ></button>');
}
}
$("#board").append("<br/>");
}
$(".tile").width(100/cols);
$(".tile").height(100/rows);
console.log("bombs: " + numBombs, "possible: " + possibleBombs);
}
$(".tile").on('click', function() {
$(this).css("color", "black");
console.log("clicked");
});
function boardClear() {
$("#board").empty();
}
You can see that my $(".tile") on click function has the word "clicked" logged to console, but that never happens when I click on one.
I have tried wrapping the on click function in $(document).ready(function(){}), but it still does not work.
You need to use
$(document).on('click', '.tile', function() {
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
I made the change in your HTML and tested it and works as expected. Cheers!

jQuery mouseenter only works on first page load

This code presents a grid of colored cells that change color on mouseenter, leaving a trail of cells of the new color. A button reloads the grid with cells of the original color. Problem is the mouseenter color change works only after the first grid load (on page refresh) but not on subsequent loads after the Create New Grid button is clicked.
I am new to javascript and jQuery and though I've been over the class materials and read some articles on how to do various parts of this, I cannot see what is wrong.
Visit the jsfiddle here.
var gridWidth = 600;
var fillGrid = function(){
$('.grid').empty();
var cellsPer = prompt('How many cells would you like in a side?');
console.log('cellsPer = ' + cellsPer);
var cellWidth = (gridWidth / cellsPer) - 1;
console.log('cellSize = ' + cellWidth);
var cell = "<div class='cell'></div>";
for (var i = 0; i < cellsPer**2; i++) {
$('.grid').append(cell);
};
$('.cell').css({
'background':'blue','height': cellWidth+'px', 'width': cellWidth+'px',
'float':'left','margin': '0 1px 1px 0'
});
};
$(document).ready(function() {
fillGrid();
$('.grid').css({'width': gridWidth+'px'});
$('button').click(function(){
fillGrid();
});
$('.cell').mouseenter(function() {
$(this).css('background','pink');
});
});
You where adding the mouseenter event listener only once on $(document).ready.
When fillGrid() gets called, a new set of '.cell' elements not bound to the mouseenter event get added to DOM.
You must tell them to behave the same again.
See the following snipped:
var gridWidth = 600;
var fillGrid = function(){
$('.grid').empty();
var cellsPer = prompt('How many cells would you like in a side?');
console.log('cellsPer = ' + cellsPer);
var cellWidth = (gridWidth / cellsPer) - 1;
console.log('cellSize = ' + cellWidth);
var cell = "<div class='cell'></div>";
for (var i = 0; i < cellsPer**2; i++) {
$('.grid').append(cell);
};
$('.cell').css({
'background':'blue','height': cellWidth+'px', 'width': cellWidth+'px',
'float':'left','margin': '0 1px 1px 0'
});
$('.cell').mouseenter(function() {
$(this).css('background','pink');
});
};
$(document).ready(function() {
fillGrid();
$('.grid').css({'width': gridWidth+'px'});
$('button').click(function(){
fillGrid();
});
});
button{
display:block;
margin:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Create New Grid</button>
<div class="grid"></div>
Move it outside $(document).ready function and add the mouse enter functionality as
' $(document).on('mouseenter','.cell',function() {
$(this).css('background','pink');
});'
Two issues I notice with this code
1) cellsPer ** 2 is not valid. Use Math.pow or cellsPer * cellsPer
2) You are only setting up the mouse enter listener on document.ready. Calling empty on your grid will remove all child elements - attached event listeners and all. This means you will need to re-add the event listeners every time you re-initialize the grid.
Here is an updated snippet with minimal changes to get your code working:
var gridWidth = 600;
var fillGrid = function(){
$('.grid').empty();
var cellsPer = prompt('How many cells would you like in a side?');
console.log('cellsPer = ' + cellsPer);
var cellWidth = (gridWidth / cellsPer) - 1;
console.log('cellSize = ' + cellWidth);
var cell = "<div class='cell'></div>";
for (var i = 0; i < cellsPer * cellsPer; i++) {
$('.grid').append(cell);
};
$('.cell').css({
'background':'blue','height': cellWidth+'px', 'width': cellWidth+'px',
'float':'left','margin': '0 1px 1px 0'
});
};
$(document).ready(function() {
fillGrid();
$('.grid').css({'width': gridWidth+'px'});
$('button').click(function(){
fillGrid();
$('.cell').mouseenter(function() {
$(this).css('background','pink');
});
});
$('.cell').mouseenter(function() {
$(this).css('background','pink');
});
});
button{
display:block;
margin:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Create New Grid</button>
<div class="grid"></div>
Since you're doing this for a class I'm not going to refactor the code but, one other suggestion I would make is adding the event listener in the fillGrid function, that way you neatly encapsulate everything that has to do with the grid in one place.

How to display an image associated with a clicked list item

I need help with a school project. I have a catClicker app that displays an image of a cat and the number of times the image has been clicked.
Now I have to display the names of five different cats. When a cat's name is clicked, I have to update the image and counter for that cat.
This is what I've done so far:
https://github.com/silvodesigns/catClicker
Change your cats object like this
var cats = {'Tabby' : {'count' : 0, 'src' : 'img/Cat01.jpg'}, 'Tiger' : {'count' : 0, 'src' : 'img/Cat02.jpg'}};
Explanation :
We are keeping the cat name as the key to the individual cat properties so we can fetch them using the cat name on click.
For your event handler
$("ul#cats>li").on("click", function(){
var name = $(this).html();
var src = cats[name].src;
$('img.cat').attr('src',src);
cats[name].count = cats[name].count + 1;
});
Explanation :
Jquery is being used as i can see you are using jquery.js.
We fetch the name using html property.
We then pass it as the key to cats object to get the property such as name and count.
Note: I have added only two cats , add more if you have them :D
Register a click event handler on the image container (use event delegation).
On each click increment the counter, in that way you can maintain the number of clicks.
On click of name, do the same. Register a click event handler and on click get the image name from the event.target and then change the main image as per it.
There is many solution to do the same. Here is the solution from my side.
Your previous code for appending the name is:
for(var i=0; i< catNames.length; i++){
$('#cats').append('<li>'+ catNames[i].name +'</li>');// loop over the names of the cats and create and append it to the ul on Index.html
}
I make a little change. Used data attribute to stored the index for each name (li)
for(var i=0; i< catNames.length; i++){
$('#cats').append('<li data-index="'+i+'" class="names">'+ catNames[i].name +'</li>');// loop over the names of the cats and create and append it to the ul on Index.html
}
and your onclick target is different as previous:
$('.cat').click(function(){// whenever the picture with class .cat is clicked the counter goes up
catNames[model.currentCat].clickCount ++;
var counter = document.getElementById("counter");
counter.innerHTML = catNames[model.currentCat].clickCount;
}
The update version for the click event is like this:
** i used names as class for each li
$('.names').click(function(){
// whenever the picture with class .cat is clicked the counter goes up
var index=parseInt($(this).data("index"));
var image=catNames[index].imgSrc;
//This line count individual click for each
catNames[index].clickCount= catNames[index].clickCount+1
catNames[model.currentCat].clickCount ++;
var counter = document.getElementById("counter");
counter.innerHTML = catNames[model.currentCat].clickCount;
$('.cat').attr('src',image);
}
The problem you're facing is that when an HTML list item is clicked, the click handler has to figure out which logical cat object it should update.
Here is a simple solution: when you make the list item, add a property that refers to the cat object.
Like this:
var listItem = $('<li>').html(cat.name);
$('#catList').append(listItem);
listItem = listItem[0]; // Extract the DOM element from the jQuery object.
listItem.cat = cat; // Add a reference to the logical cat object.
listItem.onclick = function () {
var cat = this.cat; // When the list item is clicked, get the cat object.
cat.clickCount++; // Increment the counter and update the display.
$('#displayClickedCat').html(
'<p id="counter">' + cat.name + ' has ' + cat.clickCount +
' click' + (cat.clickCount == 1 ? '' : 's') +
'.</p>' + '<img src="' + cat.src + '" class="cat" />');
};
The snippet below demonstrates this approach.
var imageDirectory =
'https://raw.githubusercontent.com/silvodesigns/catClicker/master/img/';
var model = {
startCat: 0,
cats: [
{ name: 'Tabby', src: imageDirectory + 'Cat01.jpg' },
{ name: 'Scaredy', src: imageDirectory + 'Cat02.jpg' },
{ name: 'Sleepy', src: imageDirectory + 'Cat03.jpg' },
{ name: 'Shadow', src: imageDirectory + 'Cat04.jpg' },
{ name: 'Tiger', src: imageDirectory + 'Cat05.jpg' }
]
};
$(document).ready(function () {
var cats = model.cats;
for (var i = 0; i < cats.length; i++) {
var cat = cats[i];
cat.clickCount = 0;
var listItem = $('<li>').html(cat.name);
$('#catList').append(listItem);
listItem = listItem[0]; // Extract the DOM element from the jQuery object.
listItem.cat = cat; // Add a reference to the logical cat object.
listItem.onclick = function () {
var cat = this.cat; // When the list item is clicked, get the cat object.
cat.clickCount++; // Increment the counter and update the display.
$('#displayClickedCat').html(
'<p id="counter">' + cat.name + ' has ' + cat.clickCount +
' click' + (cat.clickCount == 1 ? '' : 's') +
'.</p>' + '<img src="' + cat.src + '" class="cat" />');
};
if (i == model.startCat) {
cat.clickCount = -1;
listItem.onclick();
}
}
});
body {
font-family: sans-serif;
padding-left: 10px;
font-size: 18px;
}
img {
}
#catList {
list-style: none;
padding: 0;
}
#catList li {
display: inline;
margin: 5px 10px 5px 0;
padding: 5px 12px;
border: 1px solid #bbb;
border-radius: 5px;
cursor: pointer;
}
#catList li:hover {
border-color: #888;
background: #f4f4f4;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="displayNames">
<ul id="catList"></ul>
</div>
<div id="displayClickedCat"></div>

FadeIn div content one by one

I have some content in div, basically div will be hide, now i want when i press button the div content will be show with fadeIn function, now my problem i want show the div content one by one means one alphabet fadeIn then other but in my case it will be done word by word.
HTML
<div>
<span> THIS IS EXAMPLE OF FADE IN WORLD ONE BY ONE IN ALPHABETIC ORDER</span>
</div>
<input type='button' value='click me'/>
JS
$("input[type=button]").click(function(){
$("div").show();
$("span").each(function(index) {
$(this).delay(400*index).fadeIn(300);
});
});
CSS
div { display:none }
Fiddle Here
The trick is to split your span into smaller spans, one for every letter, and to use setTimeout to fade those spans one after the other :
$("input[type=button]").click(function(){
var $div = $('div');
$div.html($div.text().split('').map(function(l){
return '<span style="display:none;">'+l+'</span>'
}).join('')).show().find('span').each(function(i, e){
setTimeout(function(){ $(e).fadeIn() }, i*100);
});
});
Demonstration
you could also do:
$("input[type=button]").click(function(){
$("div").find("span").hide();
$("div").show();
var spanEle = $("span"),
contentArray = spanEle.text().split(""),
current = 0;
spanEle.text('');
setInterval(function() {
if(current < contentArray.length) {
spanEle.text(spanEle.text() + contentArray[current++]).fadeIn("slow");
}
}, 100);
});
Demo:: jsFiddle
DEMO
$(function () {
$('#test').click(function () {
var dest = $('div span#char');
var c = 0;
var string = dest.text();
dest.text('').parent().show();
var q = jQuery.map(string.split(''), function (letter) {
return $('<span>' + letter + '</span>');
});
var i = setInterval(function () {
q[c].appendTo(dest).hide().fadeIn(1000);
c += 1;
if (c >= q.length) clearInterval(i);
}, 100);
});
});
Demo http://jsfiddle.net/krasimir/4GmSF/1/
HTML
<div>THIS IS EXAMPLE OF FADE IN WORLD ONE BY ONE IN ALPHABETIC ORDER</div>
<input type='button' value='click me'/>
CSS
div {
display: none;
}
div span {
opacity: 0;
}
JavaScript
var transformText = function(selector) {
var div = $(selector);
var words = div.text().split(" ");
var newHTML = '';
for(var i=0; word=words[i]; i++) {
newHTML += '<span>' + word + '</span> ';
}
div.html(newHTML);
}
$("input[type=button]").click(function(){
transformText("div");
$("div").show();
$("div span").each(function(index) {
(function(span, index) {
setTimeout(function() {
span.css("opacity", 0);
span.animate({
opacity: 1
});
}, index*100);
})($(this), index);
});
});

Categories