Javascript dynamically created Divs [duplicate] - javascript

This question already has answers here:
What is the difference between "let" and "var"?
(39 answers)
Closed 12 months ago.
This is a simple javascript code. I'm creating 5 divs in script and populate an 'onclick' event for each. However, all of them give me the id of the last one. Any idea why this behavior occurring? Many thanks.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<style type="text/css">
.divImgPoint {
float: left;
border-radius: 50%;
width: 15px;
height: 15px;
margin-left: 5px;
margin-right: 5px;
border: ridge 2px #c73756;
}
.divTest {
position: absolute;
width: 100px;
height: 100px;
top: 200px;
left: 100px;
border: 1px solid red;
}
</style>
<script type="text/javascript">
function createNewDivs() {
var divFixed = document.getElementById('divFixed');
var newDiv;
for (xI = 0; xI < 5; xI++) {
newDiv = document.createElement('div');
newDiv.id = "newDiv_" + xI;
newDiv.className = "divImgPoint";
newDiv.onclick = () => { alert(newDiv.id + " | " + xI); }
divFixed.appendChild(newDiv);
}
}
</script>
</head>
<body>
<div id="divFixed">
</div>
</body>
</html>
<script type="text/javascript">
window.addEventListener('load', () => { createNewDivs(); });
</script>

Put let newDiv; inside loop.
Like
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<style type="text/css">
.divImgPoint {
float: left;
border-radius: 50%;
width: 15px;
height: 15px;
margin-left: 5px;
margin-right: 5px;
border: ridge 2px #c73756;
}
.divTest {
position: absolute;
width: 100px;
height: 100px;
top: 200px;
left: 100px;
border: 1px solid red;
}
</style>
<script type="text/javascript">
function createNewDivs() {
var divFixed = document.getElementById('divFixed');
for (xI = 0; xI < 5; xI++) {
let newDiv;
newDiv = document.createElement('div');
newDiv.id = "newDiv_" + xI;
newDiv.className = "divImgPoint";
newDiv.onclick = () => { alert(newDiv.id + " | " + xI); }
divFixed.appendChild(newDiv);
}
}
</script>
</head>
<body>
<div id="divFixed">
</div>
</body>
</html>
<script type="text/javascript">
window.addEventListener('load', () => { createNewDivs(); });
</script>

Related

Parent and child relationship not working

I am not quite sure how to phrase my question, so please forgive me. My plan was to create giant images of letters that make up the words "Hello World". I wanted to have these words nest inside of the big boxes and later decided to have each word be inside a smaller box. In the picture, I have created a small box (the sized has not been permanently set, I was just testing). But when I created the second small box, it flew out of the big box. In my index.html file, the <div> for the second small box was nested inside the big box div.
Here is the code:
INDEX.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="script.js"></script>
<div class = "box">
<div class = "hello-box"></div>
<div class = "h-left"></div>
<div class = "h-mid"></div>
<div class = "h-right"></div>
</div>
<div class = "world-box">
</div>
</div>
</body>
</html>
STYLE.CSS
body {
background-color: skyblue;
}
.box {
position: relative;
margin: auto;
margin-top: 15%;
display: block;
border: 3px solid black;
width: 800px;
height: 500px;
}
.hello-box {
position: relative;
margin: auto;
margin-top: 125px;
width: 100px;
height: 100px;
border: 1px solid black;
}
.world-box {
position: relative;
margin: auto;
margin-top: 125px;
width: 100px;
height: 100px;
border: 1px solid black;
}
RESULT
Any help would very appreciated!!!
.flex-container {
display: flex;
flex-wrap: nowrap;
background-color: DodgerBlue;
}
.flex-container > div {
background-color: #f1f1f1;
width: 100px;
margin: 10px;
text-align: center;
line-height: 75px;
font-size: 30px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="script.js"></script>
<div class="flex-container">
<div>H</div>
<div>E</div>
<div>L</div>
<div>L</div>
<div>O</div>
<div>W</div>
<div>O</div>
<div>R</div>
<div>L</div>
<div>D</div>
<div>!</div>
</div>
</body>
</html>
using flexbox
Assuming you're able to modify the HTML, the easiest way to fix this would be to simply shift your .world-box <div> to be inside of your .box <div>:
body {
background-color: skyblue;
}
.box {
position: relative;
margin: auto;
margin-top: 15%;
display: block;
border: 3px solid black;
width: 800px;
height: 500px;
}
.hello-box {
position: relative;
margin: auto;
margin-top: 125px;
width: 100px;
height: 100px;
border: 1px solid black;
}
.world-box {
position: relative;
margin: auto;
margin-top: 125px;
width: 100px;
height: 100px;
border: 1px solid black;
}
<body>
<div class="box">
<div class="hello-box"></div>
<div class="h-left"></div>
<div class="h-mid"></div>
<div class="h-right"></div>
<div class="world-box"></div>
</div>
</body>
I would actually create a function that would put anything you want into some kind of wrapper, like so:
/* js/external.js */
//<![CDATA[
var doc, bod, M, I, S, Q, special, unspecial, shuffle, ReaderBoard, autoBoard, randBoard; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body;
M = function(tag){
return doc.createElement(tag);
}
I = function(id){
return doc.getElementById(id);
}
S = function(selector, within){
var w = within || doc;
return w.querySelector(selector);
}
Q = function(selector, within){
var w = within || doc;
return w.querySelectorAll(selector);
}
special = function(str){
return str.replace(/&/g, '&').replace(/'/g, '&apos;').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
}
unspecial = function(str){
return str.replace(/&/g, '&').replace(/&apos;/g, "'").replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
}
shuffle = function(array){
var a = array.slice(), l = a.length;
a.sort(function(b, c){
return 0.5 - Math.random();
});
return a;
}
ReaderBoard = function(outputElement){
this.output;
var t = this;
this.setOutput = function(element){
this.output = element;
return this;
}
this.setOutput(outputElement);
this.setText = function(text){
this.output.innerHTML = '';
for(var i=0,a=text.split(''),s,d,l=a.length; i<l; i++){
d = M('div'); s = a[i];
if(s === ' ')d.className = 'space';
d.innerHTML = special(s); this.output.appendChild(d);
}
return this;
}
}
autoBoard = function(outputElement, textArray, interval, noLoop){
var rb = new ReaderBoard(outputElement), i = 0, r, l = textArray.length;
var v = interval || 1500;
rb.setText(textArray[0]);
r = setInterval(function(){
i++;
if(i === l){
if(noLoop){
clearInterval(r); r = undefined;
return;
}
else{
i = 0;
}
}
rb.setText(textArray[i]);
}, v);
}
randBoard = function(outputElement, textArray, interval, noLoop){
var rb = new ReaderBoard(outputElement), i = 0, r, a = shuffle(textArray), l = a.length;
var v = interval || 1500;
rb.setText(a[0]);
r = setInterval(function(){
i++;
if(i === l){
if(noLoop){
clearInterval(r); r = undefined;
return;
}
else{
a = shuffle(a); i = 0;
}
}
rb.setText(a[i]);
}, v);
}
var rb = new ReaderBoard(I('readerboard'));
rb.setText('Hello World!');
autoBoard(I('autoboard'), ['Check this out!', "It's a reader board.", 'This one runs in order.', 'Are you not amazed?']);
autoBoard(I('noloop_autoboard'), ['Check this out!', "It's a reader board.", 'This one runs in order.', 'Are you not amazed?'], 2000, true);
randBoard(I('randboard'), ['This is Awesome!', "Isn't totally random.", 'Create Something Cool', 'Success!', 'Nice']);
randBoard(I('noloop_randboard'), ['This is Awesome!', "Isn't totally random.", 'Create Something Cool', 'Success!', 'Nice'], 3500, true);
});
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
.flex_text{
display:flex;
}
.flex_text>div{
flex:1; background:#fff; font:bold 30px Arial, Helvetica, sans-serif; text-align:center; margin:3px;
}
.flex_text>.space{
background:#ccc; margin:0;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div class='flex_text' id='readerboard'></div>
<hr />
<div class='flex_text' id='autoboard'></div>
<hr />
<div class='flex_text' id='noloop_autoboard'></div>
<hr />
<div class='flex_text' id='randboard'></div>
<hr />
<div class='flex_text' id='noloop_randboard'></div>
</body>
</html>
Just a thought.

Activating the "onmousemove" event only when the "onmousedown" event is activated

After discovering the difficulties of styling inputs of type range, I though it best to simply create one using css and hiding the original. I'm trying to Make a volume slider, but I don't think I fully understand how to connect onmousemove and onmousedown. I tried following the following post
How to connect onmousemove with onmousedown?
but my volumeSlider function - the javascript code that is commented out - still isn't working;
What I want is that onmousemove is only activated on onmousedown and not by simply moving the mouse.
const volume_div = document.querySelector('.volume');
const volumeBtn_div = document.querySelector('.volume-button');
function volumeClick(event) {
let x = event.offsetX;
volume_div.style.width = (Math.floor(x) + 10) + 'px';
}
/*
volumeBtn_div.onmousedown = function() {
volumeBtn_div.onmousemove = volumeSlide;
};
function volumeSlide(event) {
let x = event.offsetX;
volume_div.style.width = Math.floor(x) + 'px';
}*/
body {
background-color: #2a2a2a;
}
.volume-range {
margin-top: 80px;
height: 5px;
width: 250px;
background: #555;
border-radius: 15px;
}
.volume-range>.volume {
height: 5px;
width: 50px;
background: #2ecc71;
border: none;
border-radius: 10px;
outline: none;
position: relative;
}
.volume-range>.volume>.volume-button {
width: 20px;
height: 20px;
border-radius: 20px;
background: #FFF;
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
outline: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Volume</title <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
</head>
<body>
<div class="volume-range" onclick="volumeClick(event)">
<div class="volume">
<div class="volume-button"></div>
</div>
</div>
If I understand your question correctly, I think you could just set a flag onmousedown and reset it onmouseup. Something like:
let mouseIsDown = false;
volumeBtn_div.onmousedown = function() { mouseIsDown = true };
volumeBtn_div.onmouseup = function() { mouseIsDown = false };
volumeBtn_div.onmousemove = volumeSlide;
function volumeSlide(event) {
if(mouseIsDown){
let x = event.offsetX;
volume_div.style.width = Math.floor(x) + 'px';
}
}
...
In response to your comment, this similar example works in Chrome. I changed the EventListener syntax. It should get you on the right track.
<!DOCTYPE html>
<html>
<head>
<style>
div { width: 200px; height: 100px; border: 1px solid black; }
</style>
</head>
<body>
<div id="input"></div>
<p id="output"></p>
<script>
const input = document.getElementById("input");
const output = document.getElementById("output");
let mouseIsDown = false;
input.addEventListener("mouseup", up);
input.addEventListener("mousedown", down);
input.addEventListener("mousemove", slide);
function down(){ mouseIsDown = true; }
function up(){ mouseIsDown = false; }
function slide(e) {
if(mouseIsDown){
var x = e.clientX;
var pos = "pos: " + x;
output.innerHTML = pos;
}
}
</script>
</body>
</html>

Import array from external JS file into HTML

I try to load an array from an external JS file into my HTML and have problems with that.
My js.js:
var temp_max = [4,9,2,5,8,4,2,10];
My HTML:
Note: Please download this file DateJS and insert it into "DATE-JS"!!
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--CSS for layout-->
<link rel="stylesheet" type="text/css" href="mystyle.css">
<!--Date library for german date layout-->
<script src="DATE-JS"></script>
<script src="js.js"></script>
</head>
<body>
<br>
<br>
<div style="width:80%" position="absolute">
<div class="header">
<script>
for(var i = 0 ; i <8 ; i++)
{
var weekday=Date.today().addDays(i).toString('dddd');
document.write("<div id='div_weekday'>" + weekday + "</div>");
}
for(var i = 0 ; i <8 ; i++)
{
var day = Date.today().addDays(i).toString('dd');
document.write("<div id='div_date'>" + day + "</div>")
}
</script>
</div>
</div>
</body>
</html>
My CSS:
* {
box-sizing: border-box;
}
body {
background-color: rgb(86,86,85);
}
h1:after {
content: " ";
width: 70.5%;
height: 2px;
background-color: rgb(228,203,153);
position:absolute;
top: 50%;
margin-left: 15px
}
.header {
width: 100%;
}
.header > div {
color: rgb(228,203,153);
width: 12.5%;
float: left;
border: solid rgb(228,203,153);
border-width: 1px 1px 1px 0;
text-align: left;
word-break: break-all;
}
.header > div:first-child {
border-width: 1px;
}
#div_date {
border: none;
width: 12.5%;
font-size: 60px;
text-align: right;
border-bottom: solid rgba(228,203,153,0.3);
border-width: 0.5px;
padding-right: 1%
}
#div_weekday {
border: none;
width: 12.5%;
font-size: 20px;
text-align: left;
padding-left: 1%
}
Here is a screenshot without importing the JS array.
So I want that my temp_max array values are displayed exactly above the German weekdays!
So above the first information: 'Donnerstag' the script should display the value 4 from the array and so on.
Please note that I want to export this array from an external JS-file, I am not able to write this variable into my HTML file!
I already tried to use
document.getElementById
but this does not work for me.
If the problem just in looping over the created divs, I think you can do this.
All what you need to change is just adding a different ids to your divs.
Just use i index in your ids.
Something like this:
Creation:
for(var i = 0 ; i <8 ; i++) {
var weekday=Date.today().addDays(i).toString('dddd');
document.write("<div id='div_weekday_" + i + "'>" + weekday + "</div>");
}
Updating data:
for (var i = 0; i < 8; i++) {
document.getElementById('div_weekday_' + i).innerHTML = temp_max[i].weekday;
}

Custom textarea/contenteditable with divs inside it

I’ currently working on a website, where a user should be able to write and insert new songs with belonging chords into a database.
To sum things up, and get to the point pretty quick, here is my problem:
I have a div with the id “#textarea”, and the attribute contenteditable=“true”. On each enter/linebreak, I would like to create a new div with the class “.chords” and the attribute contenteditable=“false”. This ".chords" div should be placed right before the new line, like the image shows here:
The red color is the #textarea div, and the blue color the .chords divs
So my question is: how do I do this?
I’ve posted the code I've tried in the end of this post, but as you see if you run it, the .chords divs are positioned below the new line, so I’m now a bit stuck.. If any of you guys have an idea on how to do this, please let me hear from you!
$(function(e) {
$('#textarea').keydown(function(e) {
var i = 0;
// Check if the returnkey is being pressed
if (e.keyCode === 13) {
$("#textarea div:last-of-type").after("<div class=\"chords\" id=\"" + (i + 1) + "\" contenteditable=\"false\"></div>");
i = i + 1;
}
});
})
#textarea {
border: 1px solid black;
line-height: 50px;
font-size: 20px;
}
.chords {
height: 30px;
border: 1px solid black;
position: relative;
}
#textarea div:not(.chords) {
margin-top: 20px;
min-height: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textarea" contenteditable="true">
<div class="chords" id="1" contenteditable="false"></div>
<div></div>
<!--End of #textarea-->
</div>
Similar Something like that
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#textarea {
border: 1px solid red;
line-height: 50px;
font-size: 20px;
min-height: 40px;
}
.chords {
height: 30px;
border: 1px solid black;
position: relative;
margin-top:5px;
}
#textarea div:not(.chords) {
margin-top: 20px;
min-height: 40px;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(e) {
$('#textarea').keydown(function(e) {
var i = 0;
// Check if the returnkey is being pressed
if (e.keyCode === 13) {
$(this).after('<div class="chords" id="'+ (i + 1) +'" contenteditable="false"></div><div>'+$(this).html()+'</div>');
$(this).html("");
i = i + 1;
}
});
})
</script>
<div id="textarea" contenteditable="true">
</div>
<div class="chords" id="1" contenteditable="false"></div>
<div></div>
<!--End of #textarea-->
</body>
</html>
Check it out
https://jsfiddle.net/emarufhasan/66L2ohnp/?utm_source=website&utm_medium=embed&utm_campaign=66L2ohnp

Javascript to get images from Json file and button next and previous functionality

enter image description here I am trying to get images from json file. when i click on the next button next image must come and when i press previous button previous image must come.I am getting image path but it is not showing image inside div. Please help me.
function main() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
var x =document.getElementById("guitarimg");
var y =myObj.allProducts[0].image_path;
x.innerHTML = "<img src='y'>"
}
};
xmlhttp.open("GET", "guitardata1.json.txt", true);
xmlhttp.send();
}
main();
#div1
{
border: 1px solid black;
height: 700px;
width:800px;
float: left;
position: relative;
left: 250px;
top: 50px;
}
#demo
{
position: relative;
top: 30px;
}
div.navbar
{
border:1px solid black;
height:40px;
width:600px;
position: relative;
left: 80px;
top: 15px;
}
#guitarimg
{
border: 1px solid;
position: relative;
height:300px;
width: 500px;
top: 30px;
left: 120px;
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="guitar.js"></script>
<link rel="stylesheet" type="text/css" href="guitar.css">
</head>
<body>
<div id="div1">
<div class="navbar"></div>
<div id="demo">
</div>
<div id="guitarimg"></div>
</div>
</body>
</html>
basic string concatenation. y in your image tag is a string, not a variable.
var y =myObj.allProducts[0].image_path;
x.innerHTML = "<img src='y'>"
^ Not a variable
What you need to do is
var y =myObj.allProducts[0].image_path;
x.innerHTML = "<img src='" + y + "'>"
Another problem is you call the script in the head. It is possible for it to run BEFORE the element is rendered to the page. You should either set the script after the element OR call the method on document ready or window onload to ensure the div element is rendered.
I would move it to before the closing body tag.
<script type="text/javascript" src="guitar.js"></script>
</body>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
var x =document.getElementById("guitarimg");
// var y =myObj.allProducts[0].image_path;
// x.innerHTML = "<img id='img' src='" + y + "'>"
}
};
xmlhttp.open("GET", "guitardata1.json.txt", true);
xmlhttp.send();
var total =7;
var a = 0;
function next() {
// var y = myObj.allProducts.image_path;
var temp = document.getElementById("img");
//temp.innerHTML = "<img id='img' src='" + y + "'>"
if (a <= total - 1) {
//alert(x);
temp.src = myObj.allProducts[a].image_path;
a++;
}
}
function previous()
{
var temp= document.getElementById("img");
if(a >= 1)
{
temp.src = myObj.allProducts[a-1].image_path;
a--;
}
}
#div1
{
border: 1px solid black;
height: 700px;
width:800px;
float: left;
position: relative;
left: 250px;
top: 50px;
}
div.navbar
{
border:1px solid black;
height:40px;
width:600px;
position: relative;
left: 80px;
top: 15px;
}
#guitarimg
{
position: relative;
height:300px;
width: 500px;
top: 30px;
left: 120px;
}
#img
{
position: relative;
height: 300px;
width: 500px;
top: 30px;
left: 120px;
}
.button1
{
position: relative;
left: 100px;
}
.button2
{
position: relative;
left: 500px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="guitar.css">
<script type="text/javascript" src="guitar.js"></script>
</head>
<body>
<div id="div1">
<div class="navbar"></div><br><br><br>
<img id="img" src="guitarImages/main.jpg"> <br><br><br>
<button type="button" onclick="previous()" class="button1">Previous</button>
<button type="button" onclick="next()" class="button2">Next</button>
</div>
</body>
</html>
Got it thanks epascarello

Categories