vanilla javascript: element.close() not working on element - javascript

This is a Sudoko generator I'm programming in vanilla javascript:
Fiddle with code
Nicer looking full screen fiddle
If you click on one of the fields, a popup will be shown with 3x3 fields from 1 to 9. The problem is this popup can't be closed anymore, although I'm applying the close dialog.
The code how I'm generating the Sudoku board:
// create sudoku
function tableCreate() {
var body = document.getElementsByClassName("frame")[0];
var containerDiv = body.appendChild(document.createElement('div'))
containerDiv.className = 'container';
// create single cells with numbers
function createInnnerCells(parent, xx, yy) {
for (var x = 1; x <= 3; x++) {
for (var y = 1; y <= 3; y++) {
var abc = function () {
var div = parent.appendChild(document.createElement('div'))
var X = y+yy;
var Y = x+xx;
var id = 'x' + [X] + 'y' + [Y];
var cellValue = sudoku[X][Y]['value'] || '';
div.style.background = sudoku[X][Y]['background'] || 'white'
div.className = 'cell';
div.id = id;
var popover = createDialog(id);
popover.onclick = function() {
popover.close();
};
div.onclick = function() {
popover.show();
};
div.appendChild(popover);
div.appendChild(document.createTextNode(cellValue));
};
abc();
}
}
}
// create big cells for 3x3 single cells
for (var i = 0; i <= 6; i+=3) {
for (var j = 0; j <= 6; j+=3) {
var div = containerDiv.appendChild(document.createElement('div'))
div.className = 'block';
createInnnerCells(div, i, j);
}
}
}
Note that I apply the close() function to each cell:
popover.onclick = function() {
popover.close();
};
The code how I create the popup:
// create dialog
function createDialog(position){
var dialog = document.createElement('dialog');
dialog.id ='window_'+ position;
var dialogblock = dialog.appendChild(document.createElement('div'));
dialogblock.className = 'dialogblock';
for (var z = 1; z <= 9; z++) {
var div = dialogblock.appendChild(document.createElement('div'));
div.className = 'dialogcell';
div.id = position + 'z'+ z;
div.appendChild(document.createTextNode(position));
}
dialog.onclick = function() {
dialog.close();
};
return dialog;
}
I applied the close() dialog here as well
dialog.onclick = function() {
dialog.close();
};
I don't know why show() is working, but close() not?

DOM events bubble up the DOM through its parents. In your code, the dialog is a child of div. Therefore, a click event happens on dialog and then again on div which means you're closing and then opening the dialog.
You can stop the propagation of the event by using event.stopPropagation.
You can change your code like this:
popover.onclick = function(e) {
e.stopPropagation();
popover.close();
};
and
dialog.onclick = function(e) {
e.stopPropagation();
dialog.close();
};
modified your fiddle: http://jsfiddle.net/p40oahkd/9/

There's no method close() on the element you are trying to hide. You should either do element.style.display = "none" if you need to hide. Or do the following:
dialog.addEventListener('click', function() {
this.remove();
});
Check out this edit to your fiddle.

Related

Link Divblock with dynamic link

i'd like to link a divblock with the current position within the for-loop
Problem: all DivBlock get the link with the last position of the loop
my code is like this:
for (var i = 1; i <= kundenAnzahl; i++) {
var block = document.createElement("div");
block.id = i.toString();
document.getElementById(i.toString()).addEventListener('click', function() {
location.href = 'server.html?kunde='+i
}, true);
change var to let because -> https://wesbos.com/for-of-es6/
and you can assign event listeners directly to new created div element, look this code
for (let i = 0; i < 5; i++) {
var block = document.createElement('div');
block.addEventListener('click', function() {
location.href = 'server.html?kunde='+i;
}, true);
document.body.append(block);
}

Disappearing Divs in Drag and Drop

I am working on a simple drag and drop operation in JS. I have to generate the containers, since I do not know in advance how many I will need, and that seems to be leading to a couple of problems.
The first is that if I drag an item over the last div, the div disappears. I have no idea what is causing it, but it is odd.
The second is that in the drop section
box.addEventListener('drop', function(e) {
e.preventDefault();
var data = e.dataTransfer.getData('id');
e.target.appendChild(document.getElementById(data));
});
I am getting the error message: "Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'," and the 'data' is not being passed. I only get this message on JSFiddle: in both Firefox and Chrome it works fine, but I suspect that it is part of a larger issue.
I am very new at this, so any help would be appreciated.
JSFiddle here.
I think this will work for you.
I've made some changes to your javascript.
Please have a look here:
var productList = [];
for (var w = 0; w < 2; w++) {
productList.push('Apples', 'Plums', 'Rice', 'Potatoes', 'Chicken', 'Pork');
}
productList.sort();
console.log(productList.length);
var boxContainer = document.createDocumentFragment();
for (var i = 0; i < 3; i++) {
var box = boxContainer.appendChild(document.createElement("div"));
var boxID = "box" + i;
box.setAttribute('id', boxID);
box.setAttribute('class', 'dropTarget');
box.addEventListener('dragend', function(e) {
elementDragged = null;
});
box.addEventListener('dragover', function(e) {
if (e.preventDefault) {
e.preventDefault();
};
//This close was right below your Remove Class. Preventing the over class from being added
});
box.addEventListener('dragenter', function(e) {
if(this.className.indexOf('over') < 0)
//Append the className, don't remove it.
this.className += " over";
});
box.addEventListener('dragleave', function(e) {
//Now we remove it.
this.className = this.className.replace(' over','');
e.dataTransfer.dropEffect = 'move'
return false;
});
box.addEventListener('drop', function(e) {
e.preventDefault();
var data = e.dataTransfer.getData('id');
//Just preventing the HierarchyRequestError.
var parent= e.dataTransfer.getData('parent');
if(parent == e.target.id) return;
target=e.target;
//Prevent it from dragging into another div box and force it to go into the box.
if(e.target.id.indexOf('box') < 0 ) target=e.target.parentNode;
target.appendChild(document.getElementById(data));
});
document.drag = function(target, e) {
e.dataTransfer.setData("Text", 'id');
//This is the drag function that's being called. It needed the reference to the ID.
e.dataTransfer.setData('id', target.id);
//Add parentID, so we can check it later.
e.dataTransfer.setData('parent',target.parentNode.id)
}
document.getElementById("placeholder").appendChild(box);
};
for (var a = 0; a < productList.length; a++){
renderProductList(productList[a], a);
};
function renderProductList(element, index) {
console.log(element);
var nameDiv = document.createElement('div');
var itemName = element;
nameDiv.setAttribute('class','dragger');
nameDiv.setAttribute('id', itemName + index);
nameDiv.setAttribute('name', itemName);
nameDiv.setAttribute('draggable', "true");
nameDiv.setAttribute('ondragstart', 'drag(this, event)');
nameDiv.style.backgroundColor = pastelColors();
var aBox = document.getElementById('box0');
aBox.appendChild(nameDiv);
var t = document.createTextNode(element);
console.log("T: " + t);
nameDiv.innerHTML = nameDiv.innerHTML + element;
};
function pastelColors(){
var r = (Math.round(Math.random()* 127) + 127).toString(16);
var g = (Math.round(Math.random()* 127) + 127).toString(16);
var b = (Math.round(Math.random()* 127) + 127).toString(16);
pColor = '#' + r + g + b;
console.log(pColor);
return pColor;
};
function drag(target, e) {
e.dataTransfer.setData('id', target.id);
};
https://jsfiddle.net/3yLk11eb/5/
I've made comments everywhere I made changes. And there were a lot of changes to make this work smoothly.

Stop output printing multiple times if function activated more than once

I'm activating a javascript function with a Jquery onclick button:
$('#on').click(function() {
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function() {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
});
The problem is if the button is clicked more than once the function will repeat more than once. In this case it will print the output multiple times. How can I modify the javascript function to only print one character per click?
Example:
http://jsfiddle.net/874Ljaq1/
Use the jQuery event binding method one
$('#on').one("click", function() {
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function() {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
});
You can use the jQuery .data() function to set a flag when the button has been clicked once, and only proceed if the flag is not set.
The code:
$('#on').click(function () {
// if we have a flag that indicates this button has been clicked before,
// don't do anything.
if ($(this).data('clicked'))
return;
$(this).data('clicked', true); // set the flag
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function () {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
});

assign parameter value of an object javascript

I have been looking at this code for a long time trying to figure this out, but I am having no luck. This issue is that I want to assign a value to the parameter boxId. When I click on a box in the webpage an alert will come up displaying that id. I have tried many things, but nothing seems to work. I'm a beginner, so I feel at this point there just must be something that I don't know how to do.
constructor function:
function Box (boxId, name, color, number, coordinates) {
this.boxId = boxId;
this.name = name;
this.color = color;
this.number = number;
this.coordinates = coordinates;
}
global variables:
var boxes = [];
var counter = 0;
var boxId = 0;
init function:
window.onload = init;
function init() {
var generateButton = document.getElementById("generateButton");
generateButton.onclick = getBoxValues;
var clearButton = document.getElementById("clearButton");
clearButton.onclick = clear;
}
function to get values and create new boxes:
function getBoxValues() {
var nameInput = document.getElementById("name");
var name = nameInput.value;
var numbersArray = dataForm.elements.amount;
for (var i = 0; i < numbersArray.length; i++) {
if (numbersArray[i].checked) {
number = numbersArray[i].value;
}
}
var colorSelect = document.getElementById("color");
var colorOption = colorSelect.options[colorSelect.selectedIndex];
var color = colorOption.value;
if (name == null || name == "") {
alert("Please enter a name for your box");
return;
}
else {
var newbox = new Box(boxId, name, color, number, "coordinates");
boxes.push(newbox);
counter++;
var boxId = counter;
}
addBox(newbox);
var data = document.getElementById("dataForm");
data.reset();
}
function that adds boxes to the page:
function addBox(newbox) {
for (var i = 0; i < newbox.number; i++) {
var scene = document.getElementById("scene");
var div = document.createElement("div");
div.className += " " + "box";
div.innerHTML += newbox.name;
div.style.backgroundColor = newbox.color;
var x = Math.floor(Math.random() * (scene.offsetWidth-101));
var y = Math.floor(Math.random() * (scene.offsetHeight-101));
div.style.left = x + "px";
div.style.top = y + "px";
scene.appendChild(div);
div.onclick = display;
}
}
function to display alert when box is clicked:
function display(e) {
var a = e.target;
alert(a.counter);
}
function to clear boxes:
function clear() {
var elems = document.getElementsByClassName("box");
for ( k = elems.length - 1; k >= 0; k--) {
var parent = elems[k].parentNode;
parent.removeChild(elems[k]);
}
}
All of the other functions work just fine. I keep running into the id showing up as "undefined" when I click it, or the counter displaying "0" in the console log, for everything I've tried.
You can do it like this.
First, in addBox() embed boxId as an tag's attribute like this:
div.setAttribute('data-boxId', newbox.boxId);
Then in display() you can retrieve it back:
alert(e.target.getAttribute('data-boxId'));
Please tell if you do not prefer this approach and I will post an alternative (closure things).
Edit: Add jsfiddle example http://jsfiddle.net/runtarm/8FJpU/
One more try. Perhaps if you change:
var boxId = counter;
to
boxId = counter;
It will then use the boxId from the outer scope instead of the one defined in the function getBoxValues()

how to use an event object to dispaly information about a DOM element

I want to be able to click on a box (the boxes are created through code, and receive values from a form) in the webpage and display information about the box. I am working on a display() function that uses an event object and an alert to display information about the box. So far, I've had multiple odd failures in my attempt to do this, which leads me to believe that I'm not accessing object attributes correctly. I'm a beginner, so this could be really obvious, but thanks for the help.
constructor function:
function Box (counter, name, color, number, coordinates) {
this.counter = counter;
this.name = name;
this.color = color;
this.number = number;
this.coordinates = coordinates;
}
Global variables:
var boxes = [];
var counter = 0;
Init function:
function init() {
var generateButton = document.getElementById("generateButton");
generateButton.onclick = getBoxValues;
var clearButton = document.getElementById("clearButton");
clearButton.onclick = clear;
}
Function that gets values from the form:
function getBoxValues() {
var nameInput = document.getElementById("name");
var name = nameInput.value;
var numbersArray = dataForm.elements.amount;
for (var i = 0; i < numbersArray.length; i++) {
if (numbersArray[i].checked) {
number = numbersArray[i].value;
}
}
var colorSelect = document.getElementById("color");
var colorOption = colorSelect.options[colorSelect.selectedIndex];
var color = colorOption.value;
if (name == null || name == "") {
alert("Please enter a name for your box");
return;
} else {
var newbox = new Box(counter, name, color, number, "coordinates");
boxes.push(newbox);
counter++;
/*for(m = 0; m < boxes.length; m++) {
counter.newbox = boxes[m];
}*/
}
addBox(newbox);
var data = document.getElementById("dataForm");
data.reset();
}
function that assigns attributes to the boxes:
function addBox(newbox) {
for (var i = 0; i < newbox.number; i++) {
var scene = document.getElementById("scene");
var div = document.createElement("div");
div.className += " " + "box";
div.innerHTML += newbox.name;
div.style.backgroundColor = newbox.color;
var x = Math.floor(Math.random() * (scene.offsetWidth-101));
var y = Math.floor(Math.random() * (scene.offsetHeight-101));
div.style.left = x + "px";
div.style.top = y + "px";
scene.appendChild(div);
div.onclick = display;
//console.log(newbox);
//shows all of the property values of newbox in the console
//console.log(div); shows that it is an object in the console
//console.log(div.hasAttribute(number)); says false
}
}
display function:
function display(e) {
// alert(e.target); says its an html object
//alert(e.target.className); works - says "box"
//alert(e.target.hasAttribute(name)); says false
}
I've included some of the things i've found in comments.
The event object only gives you the name not a reference to the element. So... a couple of things.
First if you want to be browser agnostic you want something like (e.srcElement is for IE):
var x = e.target||e.srcElement;
Then get a reference to the element and do what you want:
var refToElement = document.getElementById(x.id);

Categories

Resources