How to make button that removes div where it is located? - javascript

I want to make button that removes div where button is located.
This current solution removes current div only temporary, BUT i want it completely be removed from this html file. Is that possible?
I am done so far:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" media="screen" type="text/css" href="styles.css"/>
<title>Orders</title>
<center>
<style>
div
{width:797px;
border:2px solid;
background-color:white;
text-align:left;
margin-bottom:2px;}
</style>
<script type="text/javascript">
function deleteline(buttonObj)
{
var node = buttonObj;
do
{
node = node.parentNode;
}
while
(node.nodeType != 1 && node.nodeName != 'div');
node.parentNode.removeChild(node);
}
</script>
</head>
<center><a href=panel.html>back</a></center>
<div>
<input type="button" onclick="deleteline(this)" value="Remove this DIV" />
</div>

BUT i want it completely be removed from this html file.
The point is all you can do using JavaScript can actually creates client-side changes, so if you really want to delete the div element from your html file, the only thing you can do is creating a Server-side API and do a XHR request to that API, then remove it on the server side.
The other way to simulate this is to set an ID on that div element and save the last state of this element in the client using localStorage, after it got deleted, like:
function deleteline(buttonObj){
var node = buttonObj;
do {
node = node.parentNode;
}
while (node.nodeType != 1 && node.nodeName != 'div');
node.parentNode.removeChild(node);
var deleted_divs = localStorage["deleted_divs"];
var deletedDivs = deleted_divs ? JSON.parse(deleted_divs) ? [];
deletedDivs.push(node.id);
localStorage["deleted_divs"] = JSON.stringify(deletedDivs);
}
then check it whenever the DOM gets loaded:
document.addEventListener("DOMContentLoaded", function(event) {
var deleted_divs = localStorage["deleted_divs"];
if(deleted_divs){
var deletedDivs = JSON.parse(deleted_divs),
i = 0,
l = deletedDivs.length;
for( ; i < l ; i++){
var el = document.getElementById(deletedDivs[i]);
if( el ){
el.parentNode.removeChild(el);
}
}
}
});

Related

JS: calling functions via buttons does not work anymore, if page is updated without reloading the page

I want to write a program with one html page, which i can update and fill with different elements via javascript with one button that stays the same in every version, which displays a modalBox. I made a very basic version of this: One page, that is filled with two buttons (next and last) for navigating through the pages and one to display the modal. In addition, i added a number, which is incremented oder decremented accordingly, when you click through the updated versions of the page.
var counter = 1;
function setUp(){
var c = document.getElementById("container");
var d = document.createElement("div");
d.setAttribute("id", "main");
d.innerHTML = counter;
var nxt = document.createElement("button");
var bck = document.createElement("button");
var modalBtn = document.createElement("button");
nxt.innerText = ">";
bck.innerText = "<";
modalBtn.innerText="Show Modal";
nxt.setAttribute("onclick","nextPage()");
bck.setAttribute("onclick","lastPage()");
modalBtn.setAttribute("onclick","showModal()");
d.appendChild(bck);
c.appendChild(d);
d.appendChild(nxt);
d.appendChild(modalBtn);
}
function showModal(){
var m = document.getElementById("modal");
m.style.display = "block";
}
function closeModal(){
var m = document.getElementById("modal");
m.style.display = "none";
}
function nextPage(){
var c = document.getElementById("container");
c.innerHTML="";
counter++;
setUp();
}
function lastPage(){
var c = document.getElementById("container");
c.innerHTML="";
counter--;
setUp();
}
setUp();
*{
padding: 0;
margin: 0;
}
#modal{
position: absolute;
width: 500px;
height: 300px;
background-color: black;
display: none;
}
#main{
background-color: aliceblue;
height: 500px;
width: 800px;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="tryout.css">
<script src="tryout.js" defer></script>
<title>Document</title>
</head>
<body>
<div id="container">
<div id="modal"><button id="closeButton" onclick="closeModal()">Close</button></div>
</div>
</body>
</html>
The problem is: on onload, the modal button works fine (on click, the modal is displayed). As soon as i update (not reloading!) the page via the next- or back button, the modal button stops working (Error-message says the type of modalbutton is null). I have no clue why, because to my knowledge, the buttons are reinitiated by clicking on the next or back button (because the setUp()-function is called in the functions triggered by the buttons). As soon as I reload the page via the reload-button, it is working until i use one of the next and back buttons.
I am new to js, it's probable that I'm missing sth. obvious here :) Many Thanks!
On the "nextPage" and "lastPage" function , you're just removing the whole content (including the modal) from the div which associated container class.
That's why when you calling the "showModal" function , there is no element with modal id on the DOM. That's why its saying null.
you can follow what Sakil said on the comment or, in your both(nextPage & lastPage) functions,you can just remove the div with id main and add it later on "setUp" function.
I'm adding some code snippet below, hope it will help;
function nextPage() {
//grab the div with "main" id
let main = document.getElementById("main");
//remove it from document
main.remove();
counter++;
//add it again; what you're doing actually.
setUp();
}
function lastPage() {
//grab the div with "main" id
let main = document.getElementById("main");
//remove it from document
main.remove();
counter--;
//add it again; what you're doing actually.
setUp();
}
of course you should refactor the code base, cause there is lot more copy-pasting staff present, but I'm leaving that up to you.

How can i put it background image on setAttribute method?

I'm making a simple program that cuts the circle evenly.
enter image description here
and I want to put it image using 'setAttribute' method.
but, It doesn't work as i thought.
here is my code.
<!DOCTYPE html>
<html lang="kr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{margin:0; padding:0;}
</style>
<script>
function elt(name, attributes){
var node = document.createElement(name);
if( attributes ){
for(var attr in attributes){
if(attributes.hasOwnProperty(attr)){
node.setAttribute(attr,attributes[attr]);
}
}
}
for(var i=2; i<arguments.length; i++){
var child = arguments[i];
if( typeof child == "string" ){
child = document.createTextNode(child);
}
node.appendChild(child);
}
return node;
}
window.onload=()=>{
const IMG_W_COUNT = 50;
const IMG_H_COUNT = 33;
const IMG_SUM = 1650;
for(var i=1,j=0;i<=IMG_SUM;i++,j+=18){
var ImageSaver = elt("div",{
class:"menu item"+i,
width:18+"px",
height:18+"px",
background:"url('paint.jpg')",
backgroundPosition:0+"px"+" "+j+"px"
});
document.body.appendChild(ImageSaver);
}
}
</script>
</head>
<body>
</body>
</html>
The elt function is a function that helps to easily generate an element.
I'd really appreciate your help.
background, height and width aren't attributes (except on a few elements, and there they are mostly deprecated), nor is backgroundPosition.
To set a CSS property value with a function use setProperty on a style declaration.
Make sure you use the CSS property name, which is background-position not backgroundPosition.
element.style.setProperty("name", "value");
You have to set CSS properties.
element.style.width=18+"px";
element.style.height=18+"px";
element.style.background="url('paint.jpg')";
element.style.backgroundPosition="top right";

Chrome - Performance Monitor - DOM Nodes keep on stacking

I'm trying to get my head around - why is the DOM Nodes keeps on going up when I'm checking my website in the Performance Monitor.
I've added this simple code that just looping on:
1) adding and element to a wrap,
2) bind it with a click event.
3) removing it.
but still the DOM Nodes are always up the I check the performance.
any thoughts?
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.wrap{
font-size:50px;
}
</style>
</head>
<body >
<div class="wrap">
<div></div>
</div>
<script>
var counter = 0;
setInterval(function () {
//increase counter (for display)
counter++;
//get wrap
var wrap = document.getElementsByClassName("wrap")[0];
//remove its children
while (wrap.firstChild) {
wrap.firstChild.removeEventListener("click", onclick);
wrap.removeChild(wrap.firstChild);
}
//create new element
var div = document.createElement("div"); // create a div element
div.innerHTML = 'hello mosh (' + counter + ')';
//bind events
div.addEventListener("click", onclick);
// append the div to wrap
wrap.appendChild(div);
}, 200);
//on click function
var onclick = function () { alert('click'); }
</script>
</body>
</html>
The v8 engine is garbage-collected, removed DOM elements are not destroyed immediately.
Occasionally unused (unreachable) objects are garbage-collected.
If I wait long enough, with your code, I do see DOM Nodes go back down to the original value (had to bump the interval to 20 to speed up the process).
For this reason it is often more efficient to not remove DOM elements, and instead just replace the HTML content.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.wrap2 {
font-size:50px;
}
</style>
</head>
<body >
<div class="wrap2">
<div></div>
</div>
<script>
var counter = 0;
var wrap = document.getElementsByClassName("wrap2")[0];
var div = wrap.getElementsByTagName("div")[0];
setInterval(function () {
counter++;
div.innerText = 'hello mosh (' + counter + ')';
}, 20);
//on click function
var onclick = function () { alert('click'); }
</script>
</body>
</html>

Auto Click all Links In Div ID

I have a WP blog page which shows recent posts using category shortcodes
On that page, i have a list of links leading to their posts.
I can't edit the links to add id or class to them, so i am manually using a div to wrap the shortcode and a javascript which makes the links open to new tab upon click, is there a way i can open all the links to new tabs open single click? (REMEMBER, I CANT EDIT THE LINKS)
Here is my codes
<!--- i cant edit the links below ----->
<div id="boss" class="boss">
Example 1
Example 2
Example 3
Example 4
</div>
JAVASCRIPT
<script type="text/javascript">
window.onload = function(){
var a = document.getElementById('boss').getElementsByTagName('a');
for (var i=0; i<a.length; i++){
a[i].setAttribute('target', '_blank');
}
}
</script>
am trying to load all the links to their new tabs upon click
<div onclick="boss();">Something To Click On</div>
ITS NOT WORKING, ANY HELP PLS?
Fullcode example:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
function boss() {
var a = document.getElementById('boss').getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
a[i].setAttribute('target', '_blank');
openNewTab(a[i], "click");
}
}
function openNewTab(obj, evtName) {
try {
if (obj.dispatchEvent !== null && obj.dispatchEvent !== undefined) {
//var event = new Event(evtName);
var event = document.createEvent("MouseEvents");
event.initMouseEvent(evtName, true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
obj.dispatchEvent(event);
} else if (obj.fireEvent !== null && obj.fireEvent !== undefined) {
event = document.createEventObject();
event.button = 1;
obj.fireEvent("on" + evtName, event);
obj.fireEvent(evtName);
} else {
obj[evtName]();
}
} catch (e) {
alert(e);
}
}
</script>
</head>
<body>
<div onclick="boss();">Something To Click On</div>
<div id="boss">
Example 1
Example 2
Example 3
Example 4
</div>
</body>
</html>
That would be easy with jQuery. You can use .each() and .attr() to achieve it.
NOTE
Try this script in your WordPress. Since the below output is a iframe, it won't work!
$ = jQuery;
$(document).ready(function(){
$("#boss > a").each(function(){
$(this).attr("target","_blank");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="boss" class="boss">
Example 1
Example 2
Example 3
Example 4
</div>
Good Luck :)

Using array element in child window to change image in parent window with getElementById

So I'm trying to complete some javascript and having trouble codeing links to update a image. In a parent window using my script I open a remote child window to operate the image. THe links on the child window open the first image and last image. Two more links control the "next" image and previous image.
Heres what I have so far
HTML PARENT WINDOW : (haven't figured out how to post html on here btw :( )
<html>
<head>
<title> </title>
<script type="text/javascript" src="scriptss.js">
</script>
</head>
<body>
<img src="images/img0.jpg" width="200px" height="200px" id="myImage" name="myImage" /></img>
<h1>XXX</h1>
<a href="#" id = "opens" >open</a>
</br>
close
</br>
</body>
<html>
Child Window HTML:
<html>
<head>
<title> Matt Beckley Assignment Remote</title>
<link rel="stylesheet" type="text/css" href="remote.css" />
<script type="text/javascript" src="scriptss.js">
</script>
</head>
<body>
<h1>My Remote</h1>
First Image
</br>
Next Image
</br>
Previous Image
</br>
Last Image
</br>
close
</body>
</html>
JAVASCRIPT child node
var newWindow = null;
window.onload = init;
var myImages = new Array();
//start loop - length depends on how many images you need to preload
for (var i=0; i<5; i++) {
//create new image object
var tempImage = new Image();
//assign name|path of image to src property of image object
tempImage.src = "img" + (i+1) + ".jpg";
}
function init()
{
for(var i=0; i<document.links.length; i++)
{
document.links[i].onclick = changeWindowState;
}
}
function windowOpen(){
if(newWindow && !newWindow.closed){
return true;
}
return false;
}
function changeWindowState()
{
if (this.id =="closes")
{
if(windowOpen())
{
newWindow.close();
}
else
{
alert("The window isn't open");
}
}
if (this.id =="closess")
{
if(windowOpen())
{
remotetest.html.close();
}
else
{
alert("The window isn't open");
}
}
if(this.id == "opens")
{
if(windowOpen())
{
alert("The Window is alreadyopen!");
}
else
{
newWindow = window.open ("remotetest.html","remoteWin","resizeable=no,width=200,height=200");
}
}
return false;
}
function first()
{
if(this.id == "first")
{
alert("box");
}
else(this.id == "first")
{
alert("box");
}
}
Anyways I'm preloading my images and I got that figured out correctly. I'm trying to access my element in the parent node in the image tag and display an array element 1-6. In other words image 1 thru image 6
THe idea is to press a button in the child node and display the first image element[0] for instand press another button element[5]
or press another button for next element[i+1] with an another button. THanks for the help.
There are quite some ways on how to communicate between parent and child window. See this for more info.

Categories