How to show/hide menu based on checkbox(s) value with JavaScript? - javascript

Update 10/4/18: I've updated the Snippet to reflected changes for anyone who may stumble upon this thread in seek of help. Existing check-boxes and newly added check-boxes will open/close the menu.
var statusChangeMenu, activeList, itemCheckBox, activeItems;
statusChangeMenu = document.getElementById("status-change-menu");
activeList = document.getElementById("active-items");
itemCheckBox = activeList.getElementsByClassName("item-checkbox");
activeItems = activeList.getElementsByClassName("active-item-text");
function addNewItem(event) {
event.preventDefault();
activeList.insertAdjacentHTML("afterbegin", "\
<li class=\"item\">\
<input class=\"item-checkbox\" type=\"checkbox\" name=\"checkbox\" />\
<span class=\"active-item-text\"></span>\
<button class=\"btn-complete\">complete</button>\
</li>");
activeItems[0].textContent = document.getElementById("new-item-text").value;
}
document.getElementById("btn-add-item").addEventListener("click", addNewItem, false);
activeList.addEventListener("change", function() {
var i, len;
for (i = 0, len = itemCheckBox.length; i < len || (i = 0); ++i) {
if (itemCheckBox[i].checked) {
i = 40;
break;
}
}
statusChangeMenu.style.height = i + "px";
}, false);
*{
margin: 0;
padding: 0;
}
body{
background-color: #393F4D;
}
header{
background-color: #1D1E22;
color: #FEDA6A;
text-align: center;
font-size: 10px;
}
main{
background-color: #707070;
max-width: 700px;
margin: auto;
margin-top: 20px;
padding: 15px;
}
#status-change-menu{
background-color: rgb(218, 123, 123);
margin-top: 10px;
height: 0px;
overflow: hidden;
transition: all .25s ease-in-out;
}
#status-change-menu>button>img{
height: 40px;
}
form{
background-color: #D4D4DC;
padding: 10px;
text-align: right;
box-shadow: 1px 1px 3px;
}
#new-item-text{
width: 100%;
}
#btn-add-item{
padding: 5px;
box-shadow: 1px 1px 3px;
}
.item-list-container{
background-color: #D4D4DC;
margin-top: 20px;
box-shadow: 1px 1px 3px;
}
.item{
background-color: rgb(165, 233, 222);
list-style: none;
display: grid;
grid-template-columns: auto 1fr max-content;
grid-template-rows: 30px;
margin-top: 10px;
}
.item-checkbox{
grid-column: 1/2;
width: 30px;
margin:auto;
}
.active-item-text{
grid-column: 2/3;
background: rgb(252, 252, 252);
overflow: hidden;
}
.btn-complete{
grid-column: 3/4;
}
.item>input{
height: 20px;
}
<body id="the-list">
<header>
<h1>The List V4</h1>
</header>
<main>
<form action="#">
<textarea name="textbox" id="new-item-text" cols="30" rows="1"></textarea>
<button type="submit" id="btn-add-item">Add</button>
</form>
<div id="status-change-menu" class="change-menu">
<h3>Status Change Menu</h3>
<button class="btn-bar-hold">BTN1<img src="img/btn_hold.svg" alt=""></button>
<button class="btn-bar-delete">BTN2<img src="img/btn_delete.svg" alt=""></button>
</div>
<div class="item-list-container">
<ul id="active-items" class="item-list">
<li class="item">
<input class="item-checkbox" type="checkbox" name="checkbox">
<span class="active-item-text">random text text random</span>
<button class="btn-complete">complete</button>
</li>
<li class="item">
<input class="item-checkbox" type="checkbox" name="checkbox">
<span class="active-item-text">random text text random</span>
<button class="btn-complete">complete</button>
</li>
</ul>
</div>
</main>
</body>
I'm working on a simple checklist web app using pure vanilla HTML, CSS, javascript. I've been stuck in one part all weekend. Hoping someone can shed some light on what I'm missing or doing wrong. Here's where I'm at.
My Goal
Whenever an item in the checklist (ul) is selected (via checkbox), a hidden menu slides out with various options to manipulate the selected item(s). The menu must stay visible if any of the checkboxes on the list are checked. The menu must close if no checkboxes are checked.
Where I'm Stuck
I'm able to get the menu to slide out during a 'change' event of the checkbox, but I can't get the menu element to react after the initial change event. During debugging, it also appears the menu element is not reacting to the checkbox is in a 'checked' state, but simply just reacting to the checkbox being changed in general. Here's the JS code I have, but I've tested various other configurations with no success.
Code Pen with Full Code & Snippet of related JS code below.
Updated Codepen 10/4/18
https://codepen.io/skazx/pen/mzeoEO?
var itemCheckBox = document.querySelectorAll('input[type="checkbox"]')
var statusChangeMenu = document.getElementById("status-change-menu")
for(var i = 0 ; i < itemCheckBox.length; i++){
itemCheckBox[i].addEventListener("change", function(){
if (!itemCheckBox.checked)
{statusChangeMenu.style.height = "40px";}
else
{statusChangeMenu.style.height = "0px";}
})}
I've read a few dozen different post and articles, but most were related to only having 1 checkbox or used jquery. Let me know if you need any further details. Thank you!

itemCheckBox refers to a NodeList returned by querySelectorAll, not an individual element, so saying itemCheckBox.checked doesn't really make sense.
You should be checking if any checkbox in the list is checked, which you can use with the .some() function, like so:
Here's a working demo
for (var i = 0; i < itemCheckBox.length; i++) {
itemCheckBox[i].addEventListener("change", function(event) {
if (!event.target.checked) {
statusChangeMenu.style.height = "40px";
} else {
statusChangeMenu.style.height = "0px";
}
});
}
var itemCheckBox = document.querySelectorAll('input[type="checkbox"]');
var statusChangeMenu = document.getElementById("status-change-menu");
function changeHandler (event) {
// get the list of checkboxes in real time in case any were added to the DOM
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var anyChecked = [].some.call(checkboxes, function(checkbox) { return checkbox.checked; });
// alternatively (instead of using .some()):
// var anyChecked = false;
// checkboxes.forEach(function (checkbox) {
// if (checkbox.checked) {
// anyChecked = true;
// }
// });
if (anyChecked) {
statusChangeMenu.style.height = "40px";
} else {
statusChangeMenu.style.height = "0px";
}
}
for (var i = 0; i < itemCheckBox.length; i++) {
itemCheckBox[i].addEventListener("change", changeHandler);
}
for (var i = itemCheckBox.length; i < itemCheckBox.length + 2; i++) {
// add some checkboxes dynamically
var newCheckbox = document.createElement("input");
var newLabel = document.createElement("label");
newLabel.innerText = "Checkbox " + (i + 1);
newCheckbox.type = "checkbox";
// -- IMPORTANT-- bind event listener on dynamically added checkbox
newCheckbox.addEventListener("change", changeHandler);
newLabel.appendChild(newCheckbox);
newLabel.appendChild(document.createElement("br"));
document.body.appendChild(newLabel);
}
#status-change-menu {
height: 0;
background-color: red;
overflow: hidden;
color: white;
font-weight: bold;
}
<div id="status-change-menu">I should be visible if any checkboxes are checked</div>
<label>Checkbox 1<input type="checkbox"/></label><br/>
<label>Checkbox 2<input type="checkbox"/></label><br/>
<label>Checkbox 3<input type="checkbox"/></label><br/>

mhodges is correct in that itemCheckBox is a NodeList, not an individual element. Another issue is that you are trying to test if the box that changed is checked, and if it isn't, you are closing the menu. As you described, that is not what you want.
You need another way to check to see if all check boxes are unchecked before you close the menu. A simple way to do that is just another inner loop in the onChange function:
for(var i = 0 ; i < itemCheckBox.length; i++){
itemCheckBox[i].addEventListener("change", function(){
showMenu = false
for(var j = 0; j < itemCheckBox.length; j++)
{
if(itemCheckBox[j].checked)
showMenu = true
}
if (showMenu)
{statusChangeMenu.style.height = "40px";}
else
{statusChangeMenu.style.height = "0px";}
})}
Heres a modified Snippet

Related

'backgroundColor' not working with javascript

I'm creating a tab menu like this:
function clear_selected() //sets all columns color black
{
var parent = document.querySelector("#container")
var items = document.querySelectorAll(".item")
var n = items.length;
for (var i = 0; i < n; i++)
items[i].style.backgroundColor = "";
}
function plus(itself) //adds another column
{
var parent = itself.parentElement;
var n = parent.childElementCount;
clear_selected();
var n = parent.querySelectorAll(".item").length;
var page = document.createElement("button");
page.className = "item";
page.style.backgroundColor = "blue";
page.textContent = "column"
page.onclick = function() {
clear_selected();
this.style.backgroundColor = "blue";
};
var temp = document.createElement("span");
temp.className = "del"
temp.innerHTML = "×"
temp.onclick = function() { //it's suppose to remove a column and color default as blue
document.querySelector("#main_item").style.backgroundColor = "blue" //THIS LINE ISN'T WORKING
this.parentElement.remove();
};
page.appendChild(temp);
parent.insertBefore(page, parent.childNodes[n]);
}
function see(el) {
clear_selected();
el.style.backgroundColor = "blue";
}
#container {
display: flex;
width: 100%;
height: 50px;
text-align: center;
background-color: yellow;
}
.item {
background-color: black;
color: white;
border: none;
outline: none;
cursor: pointer;
margin: 0.1rem;
padding: 0.1rem;
max-width: 100%;
}
.del {
background-color: red;
display: inline-block;
cursor: pointer;
border-radius: 50%;
width: 0.7rem;
margin-left: 2rem;
}
<div id="container">
<button class="item" id="main_item" style="background-color:blue;" onclick="see(this)">default column </button>
<button class="item" onclick="plus(this)">+</button>
</div>
but when I press the 'x' to remove a column, I want the default column to color blue, but the line of code which is suppose to achieve that isn't working
document.querySelector("#main_item").style.backgroundColor = "blue"
Before pressing 'x':
After pressing 'x' on the last column:
What it SHOULD look like:
I've losing sleep over this, can someone PLEASE tell me why isn't it working?
When you click on the "X", both of your onclick handlers are getting called, including the one that runs clear_selected, which sets the background color to "".
You can fix this by using stopPropagation on the event passed into the onclick function for the "x". That will stop the click event from going up the chain to the parent element of the "x".
temp.onclick = function(e) {
document.querySelector("#main_item").style.backgroundColor = "blue"
this.parentElement.remove();
e.stopPropagation();
};

Toggle Checkbox upon clicking on Span

I'm working on an assignment that needs to, upon the click of a span element's text in an input div, output the same text in an output div. That part I've done successfully, but to the left of each span element within the input div is a checkbox that needs to also be checked upon the click of said span element.
I am not allowed to target each individual checkbox with its own unique ID because I will be adding in newer checkboxes and span elements later with the press of a button and prompt. This is an assignment on event delegation.
I will then need to be able to uncheck the checkbox and remove the appended output, but first things first, I cannot figure out how to target the checkboxes. The only thing I can think of is to somehow say that whatever index number of said span element was clicked would be the index number of said checkbox is clicked, but I'm unsure if that is the best method as well as how to go about doing that.
Also, this assignment should not have any JQuery involved. My next project is actually to redo this assignment in JQuery. Any help would be appreciated!
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Canvas Document Object Model Exercise</title>
<link rel="stylesheet" href="canvas_stylesheet.css">
</head>
<body>
<div id="input">
<form>
<input class="checkbox" type="checkbox"><span class="values">Apple</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Mango</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Grape</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Strawberry</span></br></br>
<input class="checkbox" type="checkbox"><span class="values">Cherry</span>
</form>
</div>
<div id="output"></div>
CSS:
#input {
width: 250px;
height: 300px;
float: left;
padding: 20px 0 30px 15px;
border-style: solid;
border-color: black;
border-width: 1px;
}
.values {
display: inline;
}
/*
#input form input {
padding: 20px 20px 20px 20px;
}
*/
#output {
width: 225px;
height: 326px;
float: left;
border-top: 1px solid black;
border-right: 1px solid black;
border-bottom: 1px solid black;
padding: 4px 20px 20px;
}
JS:
window.onload = UncheckAll;
function UncheckAll() {
var w = document.getElementsByTagName('input');
for (var i = 0; i < w.length; i++) {
if (w[i].type == 'checkbox') {
w[i].checked = false;
}
}
}
document.getElementById("input").addEventListener("click", function(e){
if (e.target.nodeName === "SPAN") {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
}
});
Just surround your checkboxes elements with label, like I did here.
Ps: plese never write a br element like this </br>, its <br> with no slash at all
window.onload = UncheckAll;
function UncheckAll() {
var w = document.getElementsByTagName('input');
for (var i = 0; i < w.length; i++) {
if (w[i].type == 'checkbox') {
w[i].checked = false;
}
}
}
document.getElementById("input").addEventListener("click", function(e){
if (e.target.nodeName === "SPAN") {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
}
});
#input {
width: 250px;
height: 300px;
float: left;
padding: 20px 0 30px 15px;
border-style: solid;
border-color: black;
border-width: 1px;
}
.values {
display: inline;
}
/*
#input form input {
padding: 20px 20px 20px 20px;
}
*/
#output {
width: 225px;
height: 326px;
float: left;
border-top: 1px solid black;
border-right: 1px solid black;
border-bottom: 1px solid black;
padding: 4px 20px 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>Canvas Document Object Model Exercise</title>
<link rel="stylesheet" href="canvas_stylesheet.css">
</head>
<body>
<div id="input">
<form>
<label>
<input class="checkbox" type="checkbox"><span class="values">Apple</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Mango</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Grape</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Strawberry</span>
</label>
<br><br>
<label>
<input class="checkbox" type="checkbox"><span class="values">Cherry</span>
</label>
</form>
</div>
<div id="output"></div>
</body>
</html>
I realized the answer was to use .previousSibling and .nextSibling after posting the question, so I went ahead and finished all the code for the input/output part of the assignment. Then, I realized someone else mentioned .previousSibling in response to the first answer attempt. Thanks everyone!
window.onload = UncheckAll;
function UncheckAll() {
var w = document.getElementsByTagName('input');
for (var i = 0; i < w.length; i++) {
if (w[i].type == 'checkbox') {
w[i].checked = false;
}
}
}
document.getElementById("input").addEventListener("click", function(e){
//Click Input Text - Box Checks and Output Text Appears
if (e.target.nodeName === "SPAN") {
if (e.target.previousSibling.checked === false) {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
e.target.previousSibling.checked = true;
return;
}
}
//Click Input Text - Box Unchecks and Output Text Disappears
if (e.target.nodeName === "SPAN") {
if (e.target.previousSibling.checked === true) {
for (i = 0; i < document.getElementsByClassName("outputItem").length; i++) {
if (e.target.innerHTML === document.getElementsByClassName("outputItem")[i].innerHTML) {
document.getElementsByClassName("outputItem")[i].remove();
e.target.previousSibling.checked = false;
return;
}
}
}
}
//Check Box - Output Text Appears
if (e.target.type === "checkbox") {
if (e.target.checked === true) {
var node = document.createElement("P");
var textnode = document.createTextNode(e.target.nextSibling.innerHTML);
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
node.setAttribute("class", "outputItem")
return;
}
}
//Uncheck Box - Output Text Disappears
if (e.target.type === "checkbox") {
if (e.target.checked === false) {
for (i = 0; i < document.getElementsByClassName("outputItem").length; i++) {
if (e.target.nextSibling.innerHTML === document.getElementsByClassName("outputItem")[i].innerHTML) {
document.getElementsByClassName("outputItem")[i].remove();
return;
}
}
}
}
});

How to change class and text of one tag by clicking on another tag?

I don't know how to describe this without making it more complicated.
So look at the result of the code and click on the first link with "Show", then the second one and third one.
When the second link is clicked, first one closes but text remains "Hide" and i want it to change to "Show".
So, when clicking a link, detect if any other link has text "Hide" and change it to "Show".
And please no jQuery...
document.getElementsByClassName("show")[0].onclick = function() {
var x = document.getElementsByClassName("hide")[0];
var y = document.getElementsByClassName("show")[0];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[1].onclick = function() {
var x = document.getElementsByClassName("hide")[1];
var y = document.getElementsByClassName("show")[1];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[2].onclick = function() {
var x = document.getElementsByClassName("hide")[2];
var y = document.getElementsByClassName("show")[2];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
function closeOther() {
var visible = document.querySelectorAll(".visible"),
i, l = visible.length;
for (i = 0; i < l; ++i) {
visible[i].classList.remove("visible");
}
}
.style {
background-color: yellow;
width: 200px;
height: 200px;
display: inline-block;
}
.hide {
background-color: red;
width: 50px;
height: 50px;
display: none;
position: relative;
top: 50px;
left: 50px;
}
.hide.visible {
display: block;
}
<div class="style">
Show
<div class="hide">
</div>
</div>
<div class="style">
Show
<div class="hide">
</div>
</div>
<div class="style">
Show
<div class="hide">
</div>
</div>
I tried to write a solution which didn't use any javascript at all and worked using CSS alone. I couldn't get it to work though - CSS can identify focus but it can't identify blur (ie. when focus has just been removed).
So here is a solution which uses javascript and the classList API, instead:
var divs = document.getElementsByTagName('div');
function toggleFocus() {
for (var i = 0; i < divs.length; i++) {
if (divs[i] === this) continue;
divs[i].classList.add('show');
divs[i].classList.remove('hide');
}
this.classList.toggle('show');
this.classList.toggle('hide');
}
for (let i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', toggleFocus, false);
}
div {
display: inline-block;
position: relative;
width: 140px;
height: 140px;
background-color: rgb(255,255,0);
}
.show::before {
content: 'show';
}
.hide::before {
content: 'hide';
}
div::before {
color: rgb(0,0,255);
text-decoration: underline;
cursor: pointer;
}
.hide::after {
content: '';
position: absolute;
top: 40px;
left: 40px;
width: 50px;
height: 50px;
background-color: rgb(255,0,0);
}
<div class="show"></div>
<div class="show"></div>
<div class="show"></div>
Like this?
Just added following to closeOther():
visible = document.querySelectorAll(".show"),
i, l = visible.length;
for (i = 0; i < l; ++i) {
visible[i].textContent="Show";
}

How to have two different bgcolor changing events

I'm trying to have a bgcolor change for an element on mouseover, mouseout, and onclick. The problem is Javascript overwrites my onclick with mouseout, so I can't have both. So is there any way to have mouseover reset after mouseout?
function init() {
document.getElementById('default').onmouseover = function() {
tabHoverOn('default', 'grey')
};
document.getElementById('default').onmouseout = function() {
tabHoverOff('default', 'yellow')
};
document.getElementById('section2').onmouseover = function() {
tabHoverOn('section2', 'grey')
};
document.getElementById('section2').onmouseout = function() {
tabHoverOff('section2', 'yellow')
};
document.getElementById('section3').onmouseover = function() {
tabHoverOn('section3', 'grey')
};
document.getElementById('section3').onmouseout = function() {
tabHoverOff('section3', 'yellow')
};
}
function tabHoverOn(id, bgcolor) {
document.getElementById(id).style.backgroundColor = bgcolor;
}
function tabHoverOff(id, bgcolor) {
document.getElementById(id).style.backgroundColor = bgcolor;
}
var current = document.getElementById('default');
function tab1Highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab1highlight";
current = id;
}
function tab2highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab2highlight";
current = id;
}
function tab3highlight(id) {
if (current != null) {
current.className = "";
}
id.className = "tab3highlight";
current = id;
}
window.onload = init();
body {
width: 900px;
margin: 10px auto;
}
nav {
display: block;
width: 80%;
margin: 0 auto;
}
nav > ul {
list-style: none;
}
nav > ul > li {
display: inline-block;
margin: 0 3px;
width: 150px;
}
nav > ul > li > a {
width: 100%;
background-color: #ffff66;
border: 1px solid #9b9b9b;
border-radius: 12px 8px 0 0;
padding: 8px 15px;
text-decoration: none;
font-weight: bold;
font-family: arial, sans-serif;
}
main {
display: block;
width: 80%;
margin: 0 auto;
border: 1px solid #9b9b9b;
padding: 10px;
}
main > h1 {
font-size: 1.5em;
}
.tab1highlight {
background-color: #339966;
color: white;
}
.tab2highlight {
background-color: #ff6666;
color: white;
}
.tab3highlight {
background-color: #6600ff;
color: white;
}
main img {
border: 5px solid #eeefff;
width: 80%;
margin-top: 20px;
}
<body>
<nav>
<ul>
<li>Section 1</li>
<li>Section 2</li>
<li>Section 3</li>
</ul>
</nav>
<main>
<h1>Exercise: Navigation Tab #5</h1>
<ul>
<li>
Combine the navigation tab exercises #1, #3, and #4 in one file, including <br>
<ul>
<li>temporarily change the background color of a tab when the cursor is hovering on it.</li>
<li>set the foreground and background color of the tab being clicked.</li>
<li>change the background color of the main element based on the selected tab.</li>
</ul>
<p>
To test, click on a tab and then move your mouse around. For example, the third tab is clicked, the tab background color is switched to blue. Then hover the mouse over the third tab, the background color of the tab should be switch to light green and then back to blue after the mouse moves out.
</p>
<img src="menu_tab5.jpg">
</li>
</ul>
</main>
It's generally a good idea to keep CSS out of JavaScript completely if you can help it. A better strategy for solving the hover problem is to use the CSS pseudo selector :hover rather than coding the color changes in JavaScript. If you give all your tabs the same class, you only have to write the CSS once:
.tab {
background-color: yellow;
}
.tab:hover {
background-color: grey;
}
Once you've done that, you can also relegate the click styling to CSS by creating an event handler that adds and removes a special class each time a tab is clicked.
In the CSS file:
.tab.clicked {
background-color: blue;
}
And then in JavaScript, something like:
var tabs = document.getElementsByClassName('tab');
for (i = 0; i < tabs.length; i ++) {
tabs[i].onclick = function (ev) {
for (i = 0; i < tabs.length; i ++) {
tabs[i].classList.remove('clicked');
}
ev.currentTarget.classList.add('clicked');
};
}
I've created a JSFiddle to illustrate.
Try updating a Boolean variable.
var Ele = document.getElementById('default');
var clicked = false;
Ele.onclick = function(){
clicked = true;
// add additional functionality here
}
Ele.onmouseover = function(){
clicked = false;
// add additional functionality here
}
Ele.onmouseout = function(){
if(!clicked){
// add additional functionality here
}
}

Drag and Drop across browser window

I'm implementing cross-window drag-and-drop for item ordering on collaborative site and I am unable to synchronize drags to the same list. I would need to detect whether I dropped an item to the same list to avoid "add", "remove" operations and use a single "move".
NOTE: this problem involves two browser windows e.g. Firefox and Chrome; unless it works in that case, it's not suitable solution. Also, I'm not looking for a server based solution.
The gist of the problem can be demonstrated by this:
function update(source, className, d){
var count = source.getElementsByClassName(className)[0];
count.innerText = parseInt(count.innerText) + d;
}
var els = document.getElementsByClassName("source");
for(var i = 0; i < els.length; i += 1){
(function(el){
el.ondragover = function(ev){
ev.dataTransfer.dropEffect = "move";
ev.preventDefault();
ev.stopPropagation();
};
el.ondrop = function(ev){
ev.preventDefault();
ev.stopPropagation();
var id = ev.dataTransfer.getData("x/source");
if(el.dataset.id == id){
update(el, "self", 1);
// how to send a value from here to dragEnd -->>
return;
}
};
})(els[i]);
}
var els = document.getElementsByClassName("element");
for(var i = 0; i < els.length; i += 1){
(function(el){
el.draggable = true;
el.ondragstart = function(ev){
grabbingFrom = el.parentNode.dataset.id;
ev.dataTransfer.effectAllowed = "all";
ev.dataTransfer.setData("x/source", el.parentNode.dataset.id);
console.log(JSON.stringify(ev.dataTransfer.getData("x/source")));
}
el.ondragend = function(ev){
var self = false; // how to get a value <--- here
if(self){
update(el, "self", 1);
}
ev.preventDefault();
}
})(els[i]);
}
.clear { clear: both; }
.source {
float: left; border: 1px solid #000; margin: 32px;
height: 100px; width: 150px;
}
.source .element { width: 32px; height: 32px; margin: 8px;
background: #AAA; margin: 8px;
line-height: 32px; text-align: center;
}
.source .element:hover {
background: hsla(0, 70%, 70%, 1);
cursor: move;
}
<div class="source" data-id="alpha" >
Alpha
<div class="self">0</div>
<div draggable="true" class="element">X</div>
</div>
<div class="source" data-id="beta" >
Beta
<div class="self">0</div>
<div draggable="true" class="element">X</div>
</div>
When you Drag from "Beta" box to a "Beta" box in cross-windows, then both "Beta" counts should be incremented. Currently only one increments. Basically how to communicate across that "Yes, I've dropped this item into a 'beta' box.". The problem boils down to sending content from ondrop event to ondragend.
I've been unable to find a suitable way to do it. Any ideas?
Or, is the answer simply that it isn't possible.

Categories

Resources