Removing dynamic divs made with JS on click - javascript

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();
});
});

Related

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

.css file, ::first-line not possible. how to achieve this? Ubuntu 18.04

Ubuntu 18.04
i am customizing the panel, this is the content in .css file
i have added ::first-line part to cusomize first line as shown in the below image. but it is not applied after reboot.
Content of .css file:
#panel .clock-display {
color: blue; }
#panel .clock-display::first-line {
color: green; }
Content of .js file:
var DateMenuButton = new Lang.Class({
Name: 'DateMenuButton',
Extends: PanelMenu.Button,
_init() {
let item;
let hbox;
let vbox;
let menuAlignment = 0.5;
if (Clutter.get_default_text_direction() == Clutter.TextDirection.RTL)
menuAlignment = 1.0 - menuAlignment;
this.parent(menuAlignment);
this._clockDisplay = new St.Label({ y_align: Clutter.ActorAlign.CENTER });
this._indicator = new MessagesIndicator();
let box = new St.BoxLayout();
box.add_actor(new IndicatorPad(this._indicator.actor));
box.add_actor(this._clockDisplay);
box.add_actor(this._indicator.actor);
this.actor.label_actor = this._clockDisplay;
this.actor.add_actor(box);
this.actor.add_style_class_name ('clock-display');
in this last line this.actor.add_style_calss_name ('clock-display'); i guess i have to specify its pseudo_calss or something but i dont have any idea.
in the below image if you see the day with time stamp, it is the default behavior when Ubuntu is freshly installed.
by using Clock Override Extension, it is possible to make our own text..
like in this image..
here is a clue, this Clock Override Extension have special feature to make a next line by adding %n in its settings https://developer.gnome.org/glib/stable/glib-GDateTime.html#g-date-time-format
Clock Override Extension Details: https://extensions.gnome.org/extension/1206/clock-override/
Question:
i am looking to configure both lines independently in .css file to choose the colors, heights, weights, shadows, borders etc.
is it achievable?
all related files here:
https://wetransfer.com/downloads/dd97a53972b17f746225efdfa345a03220181231063516/111ced
Can you try to add a style class to a specific object?
For example: #line 475
this._clockDisplay = new St.Label({ y_align: Clutter.ActorAlign.CENTER, style_class: 'clock-label' });
CSS:
.clock-label { color: #101010; font-weight: bold; background: #fff; }
Try it.
It is working unless your text is considered as one line.
#panel .clock-display {
color: blue;
margin-left: 40px;
margin-right: 40px;
}
#panel .clock-display::first-line {
height: 40px;
width: device-width;
background: blue;}
.barfont {
height: 30px;
width: device-width;
color: blue;
font-size:15px;
font-weight: bold;
line-height:0px;
}
.barbackground {
margin: 0;
padding: 0;
height: 30px;
width: device-width;
background-color: green;
border-top-style: solid;
border-top-color: green;
line-height:0px;
}
<html>
<body background="https://i.stack.imgur.com/80hPG.png" >
<div class="barbackground">
<p class="barfont">data &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp &nbsp&nbsp&nbsp &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp &nbsp&nbsp&nbsp day first link </p></div>
</body>
</html>
Changing the first line.
.clock-display {
color: blue;
margin-left: 40px;
text-indent: 40px;
}
::first-line {
color: green;
/* WARNING: DO NOT USE THESE */
/* Many properties are invalid in ::first-line pseudo-elements */
margin-left: 20px;
text-indent: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body >
<pre class="clock-display">
121
data and time</pre>
</body>
</html>

Save contentEditable into html file with javascript

How can I save contenteditable element with javascript(no PHP) into actual HTML code? So I can edit content whenever even in offline mode.
Like when you click "save button" it replace old file with new one(text with changes).
If there is a way to make this work in offline mode with any other programming lang please suggest.
I found a few examples but they were all made with PHP.
Also, I will post code. In this code, you are able to edit the file with javascript and save it. But problem is that it does not save into actual HTML code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<style type="text/css">
body{
font-family: "Dosis";
font-size: 1.3em;
line-height: 1.6em;
}
.headline{
font-size: 2em;
text-align: center;
}
#wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
border-radius: 3px;
}
button {
border: none;
padding: 0.8em;
background: #F96;
border-radius: 3px;
color: white;
font-weight: bold;
margin: 0 0 1em;
}
button:hover, button:focus {
cursor: pointer;
outline: none;
}
#editor {
padding: 1em;
background: #E6E6E6;
border-radius: 3px;
}
</style>
<body>
<div id="wrapper">
<section>
<h1 class="headline">contentEditable Demonstration</h1>
<button id="editBtn" type="button">Edit Document</button>
<div id="editDocument">
<h1 id="title">A Nice Heading.</h1>
<p>Last Edited by <span id="author">Monty Shokeen</span>
</p>
<p id="content">You can change the heading, author name and this content itself. Click on Edit Document to start editing. At this point, you can edit this document and the changes will be saved in localStorage. However, once you reload the page your changes will be gone. To fix it we will have to retrieve the contents from localSotrage when the page reloads.</p>
</div>
</section>
</div>
<script>
var editBtn = document.getElementById('editBtn');
var editables = document.querySelectorAll('#title, #author, #content');
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem('title') !== null) {
editables[0].innerHTML = localStorage.getItem('title');
}
if (localStorage.getItem('author') !== null) {
editables[1].innerHTML = localStorage.getItem('author');
}
if (localStorage.getItem('content') !== null) {
editables[2].innerHTML = localStorage.getItem('content');
}
}
editBtn.addEventListener('click', function(e) {
if (!editables[0].isContentEditable) {
editables[0].contentEditable = 'true';
editables[1].contentEditable = 'true';
editables[2].contentEditable = 'true';
editBtn.innerHTML = 'Save Changes';
editBtn.style.backgroundColor = '#6F9';
} else {
// Disable Editing
editables[0].contentEditable = 'false';
editables[1].contentEditable = 'false';
editables[2].contentEditable = 'false';
// Change Button Text and Color
editBtn.innerHTML = 'Enable Editing';
editBtn.style.backgroundColor = '#F96';
// Save the data in localStorage
for (var i = 0; i < editables.length; i++) {
localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);
}
}
});
</script>
</body>
</html>
You'll want to use something like the downloadInnerHtml function as described here. Ideally you'll probably also want to strip out the script tag and content editable attribute before exporting because you won't want the final html page to be editable

Code works in jsfiddle but not in html page [duplicate]

This question already has an answer here:
jquery code works on codepen/jsfiddle but not html page
(1 answer)
Closed 6 years ago.
I am using code from Max lines textarea to create a textarea with only 9 lines and this code works perfectly on my jsfiddle, https://jsfiddle.net/cityFoeS/3j48cpzn/ The textarea will not limit the textarea to 9 lines like I want it to.
my HTML:
<html>
<head>
<style>
body {
background: black;
}
textarea {
overflow: hidden;
resize: none;
font-family: courier;
color: white;
outline: none;
line-height: 20px;
margin: 0;
padding: 0;
border: 0;
left: 45px;
position: absolute;
font-size: 14px;
background-color: black;
border-bottom: 1px solid white;
}
div {
font-family: courier;
color: white;
line-height:20px;
position: absolute;
font-size: 14px;
width: 29px;
border-right: 1px solid white;
border-bottom: 1px solid white;
left: 10px;
}
</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
var limit = 9; // <---max no of lines you want in textarea
var textarea = document.getElementById("splitLines");
var spaces = textarea.getAttribute("cols");
textarea.onkeyup = function() {
var lines = textarea.value.split("\n");
for (var i = 0; i < lines.length; i++)
{
if (lines[i].length <= spaces) continue;
var j = 0;
var space = spaces;
while (j++ <= spaces)
{
if (lines[i].charAt(j) === " ") space = j;
}
lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
lines[i] = lines[i].substring(0, space);
}
if(lines.length>limit)
{
textarea.style.color = 'red';
setTimeout(function(){
textarea.style.color = '';
},500);
}
textarea.value = lines.slice(0, limit).join("\n");
};
</script>
</head>
<body>
<div>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10</div><textarea rows="10" cols="50" id="splitLines" onpaste="return false;"></textarea>
</body>
</html>
The problem is that in JSFiddle, you have the option "Load Type" set to "onload" under the JavaScript options.
In your code, however, the JavaScript runs immediately, before the HTML — this will cause the error (and this is what I get when running it as a standalone HTML page):
Uncaught TypeError: Cannot read property 'getAttribute' of null
There are two solutions:
Moving the <script> tags to the end of the <body> tag. For example:
<body>
<!-- all your visible HTML elements -->
<script>
// all your JS code
</script>
</body>
Encapsulating all the JavaScript in a window.onload function or a $(function() {}) (for use with jQuery). For example:
<script>
window.onload = function() {
// all your JS code
};
</script>

Javascript function unable to access CSS styling

Javascript function unable to access CSS styling
I can't figure out why the Javascript function below is unable to access any of the CSS styling! The demo script's
idea is for a small menu of options to appear at mouse coordinates when you Right-click. Code follows...
<style type="text/css">
.MiniMenuText {
Font-family: "Comic Sans MS";
Font-size: 11px;
Font-weight: Normal;
Font-style: Normal;
Text-decoration: None;
Text-align: Left;
Color: #FFFFFF;
Height:0;}
.MiniMenuBox {
-moz-box-shadow: 3px 3px 4px #000;
-webkit-box-shadow: 3px 3px 4px #000;
box-shadow: 3px 3px 4px #000;
Padding: 1px;
Width: 175px;
Height: 80px;
Background-color: #686868;
Border-style: Solid;
Border-color: #A0AAA0;
Border-width: 1px;
Text-align: Center;}
<!--
A:hover {Color:Black; Background-color:#FFFFFF;}
-->
</style>
<script type="text/javascript">
function RunMiniMenu() {
var X=window.event.clientX;
var Y=window.event.clientY;
document.write('<div Class="MiniMenuBox"; Style="Position:Absolute; Left:'+X+'px; Top:'+Y+'px;";>');
document.write('<a Href=""; Target="_blank"; Class="MiniMenuText";>Option 1</a><br>');
document.write('<a Href=""; Target="_blank"; Class="MiniMenuText";>Option 2</a><br>');
document.write('<a Href=""; Target="_blank"; Class="MiniMenuText";>Option 3</a><br>');
document.write('<a Href=""; Target="_blank"; Class="MiniMenuText";>Option 4</a><br>');
document.write('<a Href=""; Target="_blank"; Class="MiniMenuText";>Option 5</a></div>');
}
</script>
<body oncontextmenu="RunMiniMenu(); return false;"; </body>
One error is the ; you put after every HTML attribute. The other one is mentioned by Michael Berkowski (the missing > within the body tag).
One more thing to keep in mind: When you write to the document AFTER the page has fully loaded (i.e. after the document is closed), a write to it will yield a new document that lacks the styles.
EDIT
<style>
/* Your styles here */
</style>
...
<body oncontextmenu="runMiniMenu();">
<!-- Whatever markup you need comes here! -->
<script type="text/javascript">
function runMiniMenu(e) {
var X = e.clientX,
Y = e.clientY;
var div = document.createElement('div');
div.createAttribute('class', 'MiniMenuBox');
div.createAttribute('style', 'position: absolute; left:'+X+'px ...
for ( var i=1; i < 6; i++ ) {
var a = document.createElement('a');
a.createAttribute('target', '_blank');
// You get the point!
...
div.appendChild(a);
}
document.getElementsByTagName("body")[0].appendChild(div);
return false;
}
</script>
</body>
Everyone is correct about the errors in your syntax and about document.write. Abandon document.write and you will be much better off.
If you are simply trying to put that html in the body tag after the page loads then I would use innerHTML
So it would look like this:
<script type="text/javascript">
function RunMiniMenu() {
var X=window.event.clientX;
var Y=window.event.clientY;
var body = document.getElementsByTagName("body");
body.innerHTML = "<div class='MiniMenuBox' style='position:absolute; left:"+X+"px;
top:"+Y+"px;'><a href=''; target='_blank'; class='MiniMenuText'>Option 1</a><br/></div>";
}
</script>
<body onload="RunMiniMenu(); return false;"> </body>

Categories

Resources