While loop and Jquery append Not working [duplicate] - javascript

This question already has answers here:
Why do multiple `.appendTo` calls on a newly created jQuery element only append it once?
(2 answers)
Closed 3 months ago.
First question here! Hope you can help me. I'm trying to make 16 squares side by side using a Javascript while loop but I don't understand why it doesn't work. I'm new to Javascript and jQuery so please excuse me if the answer is too simple. Thank you in advance.
$(document).ready(function() {
var divs = $("<div class='square'></div>");
var i = 0;
while (i < 17) {
$("#wrapper").append(divs);
i++;
}
});
#wrapper {
width: 600px;
margin: 70px auto;
}
.square {
width: 40px;
height: 40px;
display: inline-block;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="wrapper">
<div class="square"></div>
</div>
</body>
strong text

In the loop, in each iteration you need to create a new object, else it will be just like replacing the same element so many times
So you can just clone() the element in the loop
$(document).ready(function() {
var divs = $("<div class='square'></div>");
var i = 0;
while (i < 17) {
$("#wrapper").append(divs.clone());
i++;
}
});
#wrapper {
width: 600px;
margin: 70px auto;
}
.square {
width: 40px;
height: 40px;
display: inline-block;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div class="square"></div>
</div>

updating this part of your code :
var divs = "<div class='square'></div>";
so your code will be :
$(document).ready(function() {
var divs = "<div class='square'></div>";
var i = 0;
while (i < 17) {
$("#wrapper").append(divs);
i++;
}
});
#wrapper {
width: 600px;
margin: 70px auto;
}
.square {
width: 40px;
height: 40px;
display: inline-block;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="wrapper">
<div class="square"></div>
</div>
</body>

You want to append div so just write html code in divs var
change your code to
var divs = "<div class='square'></div>"
Instead of
var divs = $("<div class='square'></div>");

Related

Change the color to the clicked element

I want to change the color of the clicked div element. If I change the color with the color is transferred to each next click div.
How to click on the div element to change the color of that div element. First click on some div and then change color?
<html>
<head>
<style>
html, body {
overflow: display;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: white;
}
#some_id1{
width: 50px;
height: 50px;
background-color: red;
}
#some_id2{
width: 50px;
height: 50px;
background-color: red;
}
#some_id3{
width: 50px;
height: 50px;
background-color: red;
}
#some_id4{
width: 50px;
height: 50px;
background-color: red;
}
</style>
</head>
<body>
<input type="color" id="divbackgroundcolor" onchange="myFunction()">
<div id="some_id1"></div>
<div id="some_id2"></div>
<div id="some_id3"></div>
<div id="some_id4"></div>
<div id="some_id5"></div>
<script>
var div = document.getElementsByTagName("div");
var divCount = div.length;
for (var i = 0; i <= divCount; i += 1) {
div[i].onclick = function(e) {
var x = document.getElementById("divbackgroundcolor").value;
document.getElementById(this.id).style.backgroundColor = x;
};
}
</script>
</body>
</html>
Ok, so first, I don't understand why are you using id on each div, while you are having the same style for each. better do it with class
Secondly, I have looked it up a little, and what I discovered people do, is just hide the color picker (input) and trigger it on click.
In your piece of code, it would look something like this:
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
clickedDivId = this.id
document.getElementById("divbackgroundcolor").click()
};
}
function colorChange(){
var x = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = x;
}
html, body {
overflow: display;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: white;
}
#divbackgroundcolor {
position: absolute;
opacity: 0;
z-index: -1;
}
.some_style {
width: 50px;
height: 50px;
background-color: red;
}
<input type="color" id="divbackgroundcolor" onchange="colorChange()">
<div class="some_style" id="some_id1"></div>
<div class="some_style" id="some_id2"></div>
<div class="some_style" id="some_id3"></div>
<div class="some_style" id="some_id4"></div>
<div class="some_style" id="some_id5"></div>
Notice that what I did is saved the id of the div I clicked on, so I could tell on which div I have clicked.
Hope that is the answer you are looking for.
Good luck.
Your example have only to mistakes:
In HTML remove the "onclick" in your "input"
And in JS your "for" loop use "i < divCount"
Change just those lines and will work!

How to let a div become visible when the bar is full [JS]

my name is Daniel and i'm making a drinking game for school, I want to let a div to become visible when the bar is full (so you know when the bar is full and you win the game), but i have no idea how to do this...
Could you help me out?
HTML:
<div class="col-xs-12" style="display: none;" id="hiddenText">
<div id="bar" class="animated bounceInUp">
</div>
</div>
CCS:
#bar {
background-color: #F8F8F8 ;
width: 340px;
height: 24px;
margin-right: auto;
margin-left: auto;
}
#bar > div {
margin-top: 30px;
max-width: 334px;
width: 100%;
height: 16px;
background: #9d3349;
position: relative;
top: 4px;
left: 3px;
transition: width 500ms;
}
JS:
var jumpsize = 2.77, // %
body = $("body");
(container = $("#bar")), (bar = container.children("div")), (topcnt = function(
px
) {
return 100 * px / container.width();
}), (set = function(pcnt) {
bar.css({ width: pcnt + "%" });
});
body
.on("click", ".card1, .card2, .card3, .card4", function() {
set(topcnt(bar.width()) + jumpsize);
});
set(0);
The reason its not working is because u forgot to put the if statement in the function u run on click. So the if statement only runs once. and on first load it will result in false. To fix your code move the if statement in your Body.onclick.
Next time it would be smart to include the full javascript that is relative to the function.
By looking at the online code i was able to find the issue.
Hope this resolves your issues.
~Yannick
When you hit your target you need to remove the CSS styling of Display = none.
W3 schools page here for some helpful info to help you learn some more.
https://www.w3schools.com/jsref/prop_style_display.asp
The line below inserted when you reach your goal to display should make the bar appear.
document.getElementById("hiddenText").style.display = "block";
I'm not sure you want this, but try this:
var jumpsize = 2.77, // %
width = 0,
body = $("body");
(container = $("#bar")), (bar = container.children("div")), (topcnt = function(
px
) {
return 100 * px / container.width();
}), (set = function(pcnt) {
bar.css({ width: pcnt + "%" });
if(pcnt >= 100) {$('#hiddenText').show();}
});
body
.on("click", ".card1, .card2, .card3, .card4", function() {
width += jumpsize;
set(topcnt(width));
});
set(0);
#bar {
background-color: #F8F8F8 ;
width: 340px;
height: 24px;
margin-right: auto;
margin-left: auto;
}
#bar > div {
margin-top: 30px;
max-width: 334px;
width: 100%;
height: 16px;
background: #9d3349;
position: relative;
top: 4px;
left: 3px;
transition: width 500ms;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-xs-12" style="display: none;" id="hiddenText">
<div id="bar" class="animated bounceInUp">
<div></div>
</div>
</div>
<button class="card1">click me</button>
You are using jQuery so quicker will be:
$('#hiddenText').show();
Edit:
sooo
if($('#bar').children('div').width() >= 334){
$('#hiddenText').show();
}
As You can see the div with progress bar can have max od 334 px. Check if it has it and if yes then show the text. Put this in that click event
Seems to me like you're overcomplicating things a little bit with the percentage calculations. I would just add a variable for the width of the bar that starts at 0 and increase this with the jumpsize on every click. Once this new variable goes over or equals 100 you show the hidden div.
HTML
<div class="col-xs-12" id="hiddenText">
<div id="bar" class="animated bounceInUp">
<div></div>
</div>
</div>
<button id="button">Click me</button>
<div id="showOnComplete">Show me when the bar is full!</div>
CSS
#bar {
width: 340px;
height: 24px;
padding: 4px 3px;
margin: 30px auto 0;
background-color: #f8f8f8;
}
#bar > div {
position: relative;
float: left;
height: 100%;
width: 0;
max-width: 100%;
background: #9d3349;
transition: width 500ms;
}
#button {
margin: 20px auto;
display: block;
}
#showOnComplete {
width: 400px;
padding: 20px;
margin: 20px auto;
background: blue;
color: #fff;
text-align: center;
display: none;
}
JS
(function($) {
var jumpSize = 20, //increased this for the fiddle, so we don't have to click as often
barWidth = 0,
$bar,
$showOnComplete;
$(function() {
$bar = $("#bar").children("div");
$showOnComplete = $("#showOnComplete");
$(document).on("click", "#button", function() {
barWidth += jumpSize;
$bar.width(barWidth + "%");
if (barWidth >= 100) $showOnComplete.show(); //optionally add a setTimeout of 500 here to account for the final transition of the bar
});
});
})(jQuery);
I've made a fiddle for it here.

Setting a div to display none when window scroll position is greater

I need to hide the div when the window scroll position is greater than the bottom position of the div. I tried to do it myself but I'm doing something wrong. Also got another question since I need a better code to text ratio to submit this question. Why when I alert(); img_top does it say object object?
$(document).ready(function(){
var img_height = $("#head").outerHeight();
var img_top = $("#head").offset();
var img_bot = img_height + img_top;
$(window).scroll(function(){
var wind_pos = $(window).scrollTop();
$("p").html(wind_pos);
if(wind_pos > img_bot){
$("#head").addClass("hide");
}
});
});
*{
margin: 0;
padding: 0;
}
body{
height: 4000px;
}
#head{
height: 600px;
background-color: blue;
}
.hide{
display: none;
}
p{
background-color: yellow;
width: 100%;
height: 50px;
}
<div id="head">
</div>
<p>
</p>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
jQuery.offset() return object representing position of the matched element, you are suppose to read top property of it.
$(document).ready(function() {
var img_height = $("#head").outerHeight();
var img_top = $("#head").offset().top;
var img_bot = img_height + img_top;
$(window).scroll(function() {
var wind_pos = $(window).scrollTop();
$("p").html(wind_pos);
if (wind_pos > img_bot) {
$("#head").addClass("hide");
}
});
});
* {
margin: 0;
padding: 0;
}
body {
height: 4000px;
}
#head {
height: 600px;
background-color: blue;
}
.hide {
display: none;
}
p {
background-color: yellow;
width: 100%;
height: 50px;
}
<div id="head">
</div>
<p>
</p>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
img_top
is an object because
$("#head").offset();
returns an object with top and left offsets,
you have to use
$("#head").offset().top
in your calculation

Trouble applying CSS changes to dynamically created via JS/JQuery

I've been trying to alter the size of my ".square" divs that are created using JS/JQuery. I've successfully changed the size of the container div, but using the exact same code does not work for the dynamically created .square divs, despite being able to apply events the .square divs in other ways.
I've been trying to understand the problem for the last two days, and have been writing and rewriting solutions, but I think my current skills are overlooking a very simple answer.
The aim was to have the .square divs' size be determined by how many squares will be in the container. The more squares, the smaller the .square div css.
Thanks for any help anyone can give.
$(document).ready(function() {
var create = function(king) {
return $("#container").prepend("<div class='square' id=king></div>");
}
var sLoad = function() {
for (i = 0; i < 16; i++) {
$("#16").click(function() {
$("#container").prepend("<div class='square'></div>");
});
};
};
sLoad();
$("#clear").on("click", function() {
$(".square").remove();
num = prompt("How many squares would you like?");
// var containerSize = function(){
// var siz = 112 * num;
// $("#container").css({"height": siz+15+"px" , "width": siz+"px"});
// }
// containerSize()
$(".square").css({
"height": "50px",
"width": "50px"
});
var make = function(num) {
return num * num;
};
//var squareSize = function(){
// var sqr = 600 / make(num);
// $(".square").css({"height":sqr+"px" , "width":sqr+"px"});
//};
//squareSize();
for (i = 0; i < make(num); i++) {
$("#container").prepend("<div class='square'></div>");
};
});
// $(".button").click(function(){
//
//making the square dis and reappear
$("#container").on("mouseenter", function() {
$(".square").mouseenter(function() {
$(this).fadeTo("fast", 0);
}),
$(".square").mouseleave(function() {
$(this).fadeTo("fast", 1);
});
});
});
#menuContainer {
height: 45px;
width: 50%;
margin: auto;
}
#container {
width: 600px;
height: 600px;
border: 1px blue dotted;
border-radius: 2%;
margin: auto;
padding: 0px;
}
#controlDiv {
height: 30px;
width: 30px;
border: 1px dashed red;
margin: auto;
margin-top: 50%;
background-color: black;
}
.square {
width: 100px;
height: 100px;
background-color: grey;
border: 1px black dashed;
border-radius: 3%;
margin: 5px 5px 5px 5px;
display: inline-block;
}
.button {
height: 27px;
width: 70px;
background-color: gold;
border: solid 1px yellow;
text-decoration-color: blue;
border-radius: 5%;
text-align: center;
padding-top: 7px;
/*margin: auto;*/
margin-bottom: 4px;
display: inline-block;
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="menuContainer">
<div class="button" id="16">Click</div>
<div class="button" id="clear">Clear</div>
</div>
<div id="container">
<!-- <div id="controlDiv"></div> -->
</div>
<!--<div class="square"></div>-->
</body>
</html>
This fiddle should work : https://jsfiddle.net/x0x9rv30/2/
You applied the CSS on removed elements, you need to create the elements first, then you can apply CSS on it.
I just swapped two code blocks :
Before
$(".square").remove();
$(".square").css({"height":"50px" , "width": "50px"});
for (i = 0; i < make(num); i++){
$("#container").prepend("<div class='square'></div>");
};
After
$(".square").remove();
for (i = 0; i < make(num); i++){
$("#container").prepend("<div class='square'></div>");
};
$(".square").css({"height":"50px" , "width": "50px"});

Create a grid of 3 X 3 using Javascript/jquery

I have a div class called box and this div forms a square.I want to repeat this div in order to form a 3 X 3 grid.How can i do this using for loop in javascript/jquery?
.box {
background: #9E9E9E;
border:black 1px solid;
width: 180px;
height:180px;
margin:0px auto;
margin-top:0px;
cursor:pointer;
display: inline-block;
float: left;
}
Here is a simple (should be easy to understand) solution, change it as you wish according to your own needs:
NOTE: In future to not get your Question down-voted follow these links...
CSS:
.box {
background: #9E9E9E;
border: black 1px solid;
width: 180px;
height: 180px;
margin: 0 auto;
margin-top: 0;
cursor: pointer;
display: inline-block;
float: left;
}
.row {
display: block;
float:left;
width:100%;
}
JS:
function makeBlocks() {
for (var i = 0; i < 3; i++) {
var row = document.createElement('div');
row.className = "row";
for (var j = 0; j < 3; j++) {
var box = document.createElement('div');
box.className = "box";
row.appendChild(box);
}
document.getElementById('boxParent').appendChild(row);
}
}
HTML:
<div>
<div id="boxParent"></div>
</div>
<div>
<button onclick="makeBlocks();">MAKE BLOCKS</button>
</div>
EDIT:
Here's a JSFiddle link
I give you a starting point:
<div class="parent">
<div class="toCopy">div that i have to clone</div>
</div>
$( ".toCopy" ).clone().appendTo( ".parent" );
result:
<div class="parent">
<div class="toCopy">div that i have to clone</div>
<div class="toCopy">div that i have to clone</div>
</div>
if you don't have class names, you can traverse the dom with jquery traversing: https://api.jquery.com/category/traversing/
Anyway I suggest you to check the manipulation section of the api: https://api.jquery.com/category/manipulation/
Do you want something like this:
http://jsfiddle.net/sqz75b9g/8/
HTML
<div class="rows">
<div class="row0"></div>
<div class="row1"></div>
<div class="row2"></div>
</div>
JQuery Code:
$(function() {
for(var row=0;row<3;row++)
{
for(var col=0;col<3;col++)
{
$(".row"+row).append("<div class='box'></div>");
}
}
})

Categories