Add class name to a newly created div and modify style - javascript

I am trying to get a div by id, and adding an event listener to that div, in my case i am trying to implement a simple mouseover event. I am trying to create a new div element and in that element add a new class called vehicles, after adding className vehicles i am trying to modify the style attribute of width to 100px, the code provided is only for practice purposes even if it does not make sense in real life.
const myDiv = document.getElementById("div-1");
myDiv.addEventListener("mouseover", function(event) {
const newDiv = document.createElement("div");
newDiv.classList.add('vehicles');
const vehicles = document.getElementsByClassName("vehicles")[0];
vehicles.setAttribute("style", "width: 100px");
});
#div-1 {
background-color: red;
color: yellow;
width: 20px;
}
.vehicles {
border: solid 2px black;
background-color: blue;
width: 20px;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>test</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="div-1">
<p>This is a test</p>
</div>
</body>
</html>

You need to append the new created elements and then it will work:
const myDiv = document.getElementById("div-1");
myDiv.addEventListener("mouseover", function(event) {
const newDiv = document.createElement("div");
newDiv.classList.add('vehicles');
myDiv.append(newDiv); // append the new created div
const vehicles = document.getElementsByClassName("vehicles")[0];
vehicles.setAttribute("style", "width: 100px");
});
#div-1 {
background-color: red;
color: yellow;
width: 20px;
}
.vehicles {
border: solid 2px black;
background-color: blue;
width: 20px;
}
<div id="div-1">
<p>This is a test</p>
</div>
EDIT (comments):
const myDiv = document.querySelector("#div-1"); // use the modern way to select element(s)
myDiv.addEventListener("mouseover", function(event) { // this is your original code
const newDiv = document.createElement("div"); // this is also your original code
newDiv.setAttribute("style", "width: 100px; background: black; height: 1em;"); // instead of adding class and manipulate it you can set the desired property via inline style
myDiv.append(newDiv); // append the new created div
});
#div-1 {
background-color: red;
color: yellow;
width: 20px;
}
<div id="div-1">
<p>This is a test</p>
</div>

You have just created a new element. You must add this element to the DOM tree.
For example,
document.body.appendChild(newDiv);

Related

Through javascript, how do I add a div to my html script with another div inside of it?

I am trying to create a notes app where the user can press a button, type text, which will spawn a box consisting of the text, which can be stretched and dragged around the screen. The part I am having trouble on is when the button is pressed and the text is inserted, the first div will spawn, but the child div isn't being spawned properly and acts strange.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="Filler/Style.css">
</head>
<body>
<button type="button" id="button">Add Filler</button>
<script src="Sketch.js"></script>
<script src="Filler/Sketch.js"></script>
<script src="Sidebar/Sketch.js"></script>
</body>
</html>
CSS
#mydiv {
position: absolute;
background-color: pink;
border: 1px solid black;
width: 200px;
height: 200px;
z-index: 4;
/* div able to be resised and scroll bar will be added if contents is too long .hidden*/
resize: both;
overflow: scroll;
/* create rounded borders */
border-radius: 15px;
-moz-border-radius: 15px;
text-align: center;
}
#mydivheader {
cursor: move;
z-index: 10;
}
Javascript
var myButton = document.getElementById("button");
myButton.addEventListener("click", clicked);
function clicked(){
const content = prompt("Div Contents");
const div = document.createElement('div');
const div2 = document.createElement('div');
div.id = "mydiv";
div.textContent = content;
div2.id = "mydivheader";
div2.style = "width: 100%; height: 15px;";
div2.textContent = content;
document.body.append(div);
div.appendChild(div2);
}
i didn't understood ur question properly.
is that the problem with content being generated twice. like one inside the parent div and another inside the child.
if so try this
function clicked(){
const content = prompt("Div Contents");
const div = document.createElement('div');
const div2 = document.createElement('div');
div.id = "mydiv";
div2.id = "mydivheader";
div2.style = "width: 100%; height: 15px;";
div2.textContent = content;
document.body.append(div);
div.appendChild(div2);
}

.last.removeClass() on recently double clicked element

I have this program that allows the user to edit a div when the user double clicks it. I'm trying to only make the most recent double clicked div have a border. I'm doing this right now with the addClass method, I add the .selceted class with this function:
$(function () {
$("div").dblclick(function (e) {
clickedTD = event.target;
$(clickedTD).find(clickedTD).last.removeClass("selected").addClass("selected");
}
I'm trying to make the last selected div be deleted with this .find(clickedTD).last.removeClass("selected")
So that most recent double clicked div is the only one with the .selected class. But this didn't work and I'm unsure why.
Here is my full code:
var text;
var selectedText;
var blue = document.getElementById("blue");
var blue2 = document.getElementById("blue2");
var elementCounter = 0;
function addElement() {
var classN = event.target.id;
text = document.getElementById("input").value;
// create a new div element and give it a unique id
var newDiv = document.createElement("div");
newDiv.id = 'temp'+elementCounter;
newDiv.classList = "div";
elementCounter++
if (classN == "blue"){
newDiv.classList = "blue"
} else if (classN == "red"){
newDiv.classList = "red"
} else if (classN == "green"){
newDiv.classList = "green"
} else if (classN == "blue2"){
newDiv.classList = "blue2"
}
// and give it some content
var newContent = document.createTextNode(text);
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
$(function() {
var currentlyDragged;
$("div").draggable({
drag: function (e) {
currentlyDragged = e.target.id
selectedText = event.target;
text = $(selectedText).html();
}
});
$(function () {
$("div").dblclick(function (e) {
clickedTD = event.target;
$(clickedTD).find(clickedTD).last.removeClass("selected").addClass("selected");
}
);
});
});
document.getElementById("input").value = " ";
}
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap');
import { library } from '#fortawesome/fontawesome-svg-core'
import { fas } from '#fortawesome/free-solid-svg-icons'
import { far } from '#fortawesome/free-regular-svg-icons'
import { fab } from '#fortawesome/free-brands-svg-icons'
// Add all icons to the library so you can use it in your page
library.add(fas, far, fab)
h1, body{
font-family: 'Roboto', sans-serif;
}
.selected {
border-style: dashed;
}
div {
text-align: center;
border: 1px solid #d3d3d3;
width: 150px;
height: 30px;
padding: 10px;
cursor: move;
z-index: 10;
background-color: white;
color: blue;
}
divWhite {
text-align: center;
border: 1px solid #d3d3d3;
width: 100px;
padding: 10px;
cursor: move;
z-index: 10;
background-color: white;
color: #fff;
}
.blue {
background: linear-gradient(87deg, #5e72e4 0, #825ee4 100%);
color: white;
}
.red {
background: linear-gradient(87deg, #f5365c 0, #f56036 100%);
color: white;
}
.green {
background: linear-gradient(87deg, #2dce89 0, #2dcecc 100%);
color: white;
}
.blue2 {
background: linear-gradient(87deg, #11cdef 0, #1171ef 100%);
color: white;
}
.white {
background: white;
color: white;
}
button{
font-size: .875rem;
border: none;
border-radius: 3px;
height: 40px;
width: 90px;
text-align: center;
position: relative;
transition: all .15s ease;
letter-spacing: .025em;
text-transform: uppercase;
will-change: transform;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body style="font-family: 'Roboto', sans-serif;">
<body id="container">
<header id="inputAssignments">
<h1 id="mulAsi">Input Your Assignments for the week:</h1>
<h1 style="display:none" id="oneAsi">Input Your Assignment:</h1>
<input id="input" type="text" value="text">
<button class="blue" id="blue" onclick="addElement()" >Make it Purple</button>
<button class="red" id="red" onclick="addElement()" >Make it Red</button>
<button class="green" id="green" onclick="addElement()" >Make it Green</button>
<button class="blue2" id="blue2" onclick="addElement()" >Make it Blue</button>
<button style="display:none" id="blue2" onclick="addElement();" >input</button>
<h1 height="30px"></h1>
</header>
</header>
<script src="script.js"></script>
</body>
</html>
What you want is ...
div dbclick
Remove selected class from div (actually... div.selcted)
Add selected class to div what you dbclicked.
input[type=text] change
set input[type=text].value to div.selcted.innerHTML
When you use jQuery event,
there are two ways to get $this
Let me show you how to solve this problem.
Regular Function
$('#elementId').on('click', function(){
//1. Remove selected class from div
$('div.selected').removeClass('selected');
//2. Add selected class to $this
const $this = $(this);
$this.addClass('selected')
});
Arrow Function
$('#elementId').on('click', (_event) => {
//1. Remove selected class from div
$('div.selected').removeClass('selected');
//2. Add selected class to $this
const $this = $(_event.currentTarget); // important!
$this.addClass('selected')
});
Finally, Change event of input[type=text]
I will skip arrow function this time.
$('#someInput').on('change', function(){
const value = $(this).val();
$('div.selcted').html(value);
});
DONE!
I recommend you to set id or class to your HTML DOM.
If you set event to ['div', 'input' ...], you will get side effect
Not use div, input
Use #element001(best) or div.myElement001
bye bye

Why doesn't this code display the button after I hide it?

When I run this JavaScript code, button2 doesn't get displayed again. I'm not sure why this is happening. I am trying to use this in a game I am creating. I searched this up on Google multiple times and couldn't find an answer.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2"></button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "auto";
}
</script>
</html>
A good way to handle this and provide more reusable code is to use <element>.classList.remove() and <element>.classList.add() to set or unset a hidden class. This can also be useful for toggling with <element>.classList.toggle().
This has the added advantage of being able to set your default display style in the CSS rather than burying it in the javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
/* allows setting preferred display in CSS */
display: block;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn1" onclick="toggleBtn2()">
Toggle Button 2
</button>
<button class="btn2 hidden" id="btn2">Button 2</button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.classList.remove("hidden");
}
function toggleBtn2() {
btn2.classList.toggle("hidden");
}
</script>
</html>
There is no auto display is CSS. As tarkh mentioned in his answer, display block would insert the new button below the initial button, and other display options would have other behaviors. But the display property does not have a value auto.
This may be my opinion, but I think modern websites shouldn't use the onclick function for events. We should separate our HTML, JS and CSS. This helps with reusability. https://en.wikipedia.org/wiki/Unobtrusive_JavaScript
So I would create a solution that uses an event handler in the Javascript. Something like:
window.onload = function(){
const btn2 = document.getElementById("btn2");
const btn1 = document.getElementsByClassName("btn1");
for(let i = 0; i < btn1.length; i++) {
btn1[i].addEventListener('click', function(){
btn2.style.display = "block";
})
}
}
Maybe btn2.style.display = "block";?
Or, as #charlietfl added, btn2.style.display = "inline"; since that is what browser default is for a button
display: block means that the element is displayed as a block, as
paragraphs and headers have always been. A block has some whitespace
above and below it and tolerates no HTML elements next to it, except
when ordered otherwise (by adding a float declaration to another
element, for instance).
display: inline means that the element is displayed inline, inside the
current block on the same line. Only when it's between two blocks does
the element form an 'anonymous block', that however has the smallest
possible width.
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2">new button here</button>
</body>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "block";
}
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.btn1 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
}
.btn2 {
background-color: white;
border: 2px solid black;
border-radius: 12px;
display: none;
}
</style>
</head>
<body>
<button class="btn1" onclick="showBtn2()">
Show Button 2
</button>
<button class="btn2" id="btn2">Button 2</button>
<script type="text/javascript">
const btn2 = document.getElementById("btn2");
function showBtn2() {
btn2.style.display = "inline";
}
</script>
</body>
</html>
Use display = inline or block instead of auto.
Add some text content to button 2 like this:
<button class="btn2" id="btn2">Button 2</button>
CSS: "display: auto;"?
display does not have an auto attribute.
you can try "inline" or "block".
'''
function showBtn2() {
btn2.style.display = "inline";
}
'''
Try using
btn2.style.display = "block";
for your script because css display doesn't have that kind of attribute you
you can read it more here : more
you'll see there's no such thing as display:auto

Polymer drag-drop event object property contains parent srcElement

I'm building a simple one page app using Polymer. I have created a custom element that contains the Polymer-drag-drop demo. The action of dragging and creating a div works fine, the event object's relatedTarget property holds a reference to the correct drop div. The problem is the srcElement and target property both hold references to the shadowRoot parent polymer element, in this case "workspace-drop".
EDIT:
Logging event.currentTarget on fire also contains a reference to the parentDiv holding the colored children. <div flex horizontal style="border: 1px dotted silver;">
Code is as follows (pretty much the demo but in a polymer element):
<link rel="import" href="/components/polymer/polymer.html">
<script src="/components/webcomponentsjs/webcomponents.js">
</script>
<link rel="import" href="/components/core-drag-drop/core-drag-drop.html">
<polymer-element name="workspace-drop">
<template>
<style>
html {
font-family: 'Helvetica Neue', 'Roboto', 'Arial', sans-serif;
}
body {
height: 100vh;
margin: 0;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
.box {
display: inline-block;
width: 100px;
height: 100px;
margin: 16px;
}
.dropped {
position: absolute;
border: 1px solid black;
width: 5px;
height: 5px;
}
</style>
<div flex horizontal style="border: 1px dotted silver;">
<core-drag-drop></core-drag-drop>
<div class="box" style="background-color: lightblue;" draggable="false"></div>
<div class="box" style="background-color: orange;" draggable="false"></div>
<div class="box" style="background-color: lightgreen;" draggable="false"></div>
<div id="hello">Hello World</div>
</div>
<div id="drop" hash="test" class="box" style="border: 3px solid silver; position: relative; width: 300px; height: 300px;" draggable="false"></div>
</template>
<script>
(function(){
addEventListener('drag-start', function(e) {
var dragInfo = e.detail;
// flaw #2: e vs dragInfo.event
console.log(e.detail);
var color = dragInfo.event.target.style.backgroundColor;
dragInfo.avatar.style.cssText = 'border: 3px solid ' + color + '; width: 32px; height: 32px; border-radius: 32px; background-color: whitesmoke';
dragInfo.drag = function() {};
dragInfo.drop = drop;
});
//
function drop(dragInfo) {
var color = dragInfo.avatar.style.borderColor;
var dropTarget = dragInfo.event.relatedTarget;
if (color && dropTarget.id === 'drop') {
var f = dragInfo.framed;
var d = document.createElement('div');
d.className = 'dropped';
d.style.left = f.x - 4 + 'px';
d.style.top = f.y - 4 + 'px';
d.style.backgroundColor = color;
dropTarget.appendChild(d);
dropTarget.style.backgroundColor = color;
}
}
Polymer({
ready: function(){
}
});
})();
</script>
</polymer-element>
Any assistance is appreciated!
Figured it out. It is related to this question.
When loggin an event object, currentTarget is null, but when logging event.currentTarget it logs a value. Why is that?
Logging the event after the drag action has completed returns a reference to the object in its completed state. Logging the specific event.target property on drag-start gave reference to the correct object, on start.

Removing dynamic divs made with JS on click

My code knowledge is very limited, comes from CodeHS and Codecademy so bear with me.
So I am trying to make a list of numbers, that can be deleted on click. So far so good with the number list, but I still can't figure how to remove them when I click the div box.
I know theres JSFiddle, but I think this is best I could do:
http://www.codecademy.com/rfabrega/codebits/xZ61aJ
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=203">
<title>Lista Mundial</title>
<style>
.divContainer {
width: 35px;
height: 25px;
border: solid 1px #c0c0c0;
background-color: #e1e1e1;
font-family: verdana;
color: #000;
float: left;
}
.text {
font-size: 15px;
font-family: verdana;
color: black;
margin-top: 4px;
}
</style>
</head>
<body>
<script type="text/javascript">
for(var i = 1; i <= 639; i++){
var divTag = document.createElement("div");
divTag.id = i;
divTag.className = "divContainer";
document.body.appendChild(divTag);
var pTg = document.createElement("p");
pTg.setAttribute("align", "center");
pTg.className = "text";
pTg.innerHTML = (i);
document.getElementById(i).appendChild(pTg);
}
</script>
</body>
</html>
you have to create a function on click that deletes the target div tag:
so in your code, after creating the div element. insert this:
divTag.onclick = function(){this.parentNode.removeChild(this)};
$(document).ready(function(){
$('p').hide();
$("body").on("click",".divContainer",function(){
$(this).remove();
});
});

Categories

Resources