How do i remove the submenu using a mouseout/mouseleave event handler - javascript

I'm trying to create a submenu for a menu item, i have got as far as creating a list of items and using a mouseover event handler but the submenu just remains there. i need it to be removed once the mouse clears away from the submenu div, not the label div. The mouseover function works but the mouseout im having a problem with. I am new to using javascript and DOM
This is the code (DOM):
var creatbtndiv = document.createElement("div");
var creatbtn = document.createElement("button");
creatbtn.innerHTML = "Click Me";
var creatlbl = document.createElement("label");
creatlbl.innerHTML = "Hover Over Me ";
creatbtndiv.appendChild(creatlbl);
creatbtndiv.appendChild(creatbtn);
document.body.appendChild(creatbtndiv);
var list = function () {
var creatDiv = document.createElement("div");
creatDiv.id = "submenudiv";
creatDiv.className = "submenudiv";
var creatul = document.createElement("ul");
for(index = 0; index < 5; ++index){
li = document.createElement("li");
li.className = "list";
li.innerHTML = "Submenu" + index;
creatul.appendChild(li);
}
creatDiv.appendChild(creatul);
document.body.appendChild(creatDiv);
};
//If the cursor hovers over the label, activate this function//
creatlbl.onmouseover = function () {
var alert = confirm("yes master");
list();
};
creatDiv.onmouseout = function(){
var confirm = confirm("the mouse is out");
list.removeChild(creatDiv);
};

creatDiv its outside its scope, so this function does nothing:
creatDiv.onmouseout = function(){
//var confirm = confirm("the mouse is out");
list.removeChild(creatDiv);
};
You could put this function, after:
document.body.appendChild(creatDiv);
creatDiv.onmouseout = function(){
//var confirm = confirm("the mouse is out");
this.parentNode.removeChild(this);
};

The issue is that 'creatDiv' doesn't exist until the mouseover event occurs, and thus triggers the list() function.
You cannot attach the onmouseout event to the nonexistent creatDiv.
Suggested change:
var list = function () {
var creatDiv = document.createElement("div");
creatDiv.id = "submenudiv";
creatDiv.className = "submenudiv";
var creatul = document.createElement("ul");
for(index = 0; index < 5; ++index){
li = document.createElement("li");
li.className = "list";
li.innerHTML = "Submenu" + index;
creatul.appendChild(li);
}
creatDiv.appendChild(creatul);
document.body.appendChild(creatDiv);
creatDiv.onmouseout = function(){
document.body.removeChild( this )
};
};
This will still be not quite right, though, because the div will go away when you mouse between text, but that's another issue.

Related

How to have a div open by a button closed by clicking off when there are multiple buttons?

I have several buttons on my site that call a script to open the content into full screen and I also want to be able to click off the created div to close it. This works but after opening one container, which is deleted after, my program produces errors trying to click another button.
function closeDiv(evt) {
const maindiv = document.getElementById('div3');
let targetElement = evt.target;
do {
if (targetElement == maindiv.childNodes[1]) {
return;
}
targetElement = targetElement.parentNode;
} while (targetElement);
var viewpost = maindiv.childNodes[1];
viewpost.parentNode.removeChild(viewpost);
maindiv.classList.remove('viewcontainer');
};
function buttonClick(button) {
var div = button.parentElement.parentElement;
var clone = div.cloneNode(true);
var element = div.childNodes;
var username = element[1].innerText;
var title = element[7].innerText;
var contenttext = div.childNodes[3].value;
var clone = document.createElement('div');
clone.classList.add('viewcontainercon');
var viewuser = document.createElement('p');
viewuser.classList.add('viewcontaineruser');
var text = document.createTextNode(username);
viewuser.appendChild(text);
clone.appendChild(viewuser)
var viewtitle = document.createElement('p');
viewtitle.classList.add('viewcontainertitle');
var text = document.createTextNode(title);
viewtitle.appendChild(text);
clone.appendChild(viewtitle);
var viewcontent = document.createElement('p');
viewcontent.classList.add('viewcontainercontent');
var text = document.createTextNode(contenttext);
viewcontent.appendChild(text);
clone.appendChild(viewcontent);
document.getElementById('div3').classList.add('viewcontainer');
document.getElementById('div3').appendChild(clone);
document.addEventListener("click", function(event){
var isClickInside = button.contains(event.target);
if (!isClickInside) {
closeDiv(event);
}
});
}
The error is specifically `viewpost is undefined' in the closeDiv() function, which is strange since that shouldn't be called until after the click. Any ideas?

Why can an event not be attached in the script but in the console?

I want to dynamically create, populate and clear a list with html and javascript. The creation and population of the list work just fine, but when I want to add the delete-button to the list item I can't attach the onclick event to the newly created element. Here is my complete function, it is called every time some changes happen to the printlist array:
var printlist = [];
var awesome = document.createElement("i");
awesome.className = "fa fa-minus";
function addToList(stationid, stationname)
{
var object = {id: stationid, name: stationname};
printlist.push(object);
drawList();
}
function removeFromList(id)
{
printlist.splice(id, 1);
drawList();
}
function drawList()
{
if (printlist.length > 0)
{
document.getElementById("printListDialog").style.visibility = 'visible';
var dlg = document.getElementById("DlgContent");
dlg.innerHTML = "";
for (var i = 0; i < printlist.length; i++)
{
var item = document.createElement("li");
item.className = "list-group-item";
var link = document.createElement("a");
link.href = "#";
link.dataset.listnumber = i;
link.style.color = "red";
link.style.float = "right";
link.appendChild(awesome);
link.onclick = function(){onRemove();};
item.innerHTML = printlist[i].name + " " + link.outerHTML;
dlg.appendChild(item);
}
}
else
{
document.getElementById("printListDialog").style.visibility = 'hidden';
}
}
function onRemove(e)
{
if (!e)
e = window.event;
var sender = e.srcElement || e.target;
removeFromList(sender.dataset.listnumber);
}
I tried:
link.onclick = function(){onRemove();};
as well as
link.addEventListener("click", onRemove);
Neither of those lines successfully adds the event from the script. However when I call any of the 2 lines above from the console it works and the event is attached.
Why does it work from the console but not from the script?
link.onclick = function(){onRemove();};
doesn't work because you're not passing through the event argument. link.onclick = onRemove should work just as your addEventListener call.
However, both of them don't work because of the line
item.innerHTML = printlist[i].name + " " + link.outerHTML;
which destroys the link element with all its dynamic data like .dataset or .onclick, and forms a raw html string that doesn't contain them. They're lost.
Do not use HTML strings!
Replace the line with
item.appendChild(document.createTextNode(printlist[i].name + " "));
item.appendChild(link); // keeps the element with the installed listener

create multiple elements (list) with onclick event

I'm trying to add multiple elements to a list and each element should execute the same on click function with different parameters, the problem is the variable x gets always contains the same value for all elements of the list.
How can I add elements and call the onclick event with a different parameter?
var addQuickLabelList = function(txtList,ul) {
for (i = 0; i<txtList.length ; i++) {
var li = document.createElement("li");
li.setAttribute("data-icon", "false");
var a = document.createElement("a");
a.innerHTML = txtList[i];
li.appendChild(a);
var x = "#"+txtList[i];
a.addEventListener("click", function(){
y = x.clone();
alert(x);
} , false);// add
$(ul).append(li);
}
};
x always gets the same value because all your event handlers share the same var x variable. To scope a variable to a block, use let (or const if it won't change) instead of var.
Or you could use .forEach() on the txtList Array so that the var is scoped to the invocation of the callback.
var addQuickLabelList = function(txtList,ul) {
txtList.forEach(function(txtItem) {
var li = document.createElement("li");
li.setAttribute("data-icon", "false");
var a = li.appendChild(document.createElement("a"));
a.innerHTML = txtItem;
var x = "#"+txtItem;
a.addEventListener("click", function(){
console.log(x);
} , false);
ul.appendChild(li);
});
};
But you also don't really even need the x variable. You already set the text as the content of the a, so you can just grab that instead. Which means you could also reuse the function, which is nicer.
function handler() {
console.log("#" + this.textContent);
}
var addQuickLabelList = function(txtList,ul) {
txtList.forEach(function(txtItem) {
var li = document.createElement("li");
li.setAttribute("data-icon", "false");
var a = li.appendChild(document.createElement("a"));
a.innerHTML = txtItem;
var x = "#"+txtItem;
a.addEventListener("click", handler, false);
ul.appendChild(li);
});
};

Trying to delete element with Javascript

When a client clicks the "buy" button, I create a popup on screen which allows them to fill in a purchase form. On the poput I want to have a "x" button so they can close it and return to the main website.
The code I run to generate the popup is:
var o = document.createElement('div');
o.className = 'overlay';
var p = document.createElement('div');
p.className = 'buyticketid';
p.setAttribute('id','buy-ticket');
var cb = document.createElement('p');
cb.className = 'closeButton';
cb.setAttribute('onclick','close()');
cb.setAttribute('title','Close');
cb.setAttribute('id','close-btn');
var x = document.createTextNode('x');
cb.appendChild(x);
p.appendChild(cb);
document.getElementsByTagName('body')[0].appendChild(o);
document.getElementsByTagName('body')[0].appendChild(p);
The code I use to try and delete the popup (ID = 'buy-ticket') is:
function close(){
var element = document.getElementById("buy-ticket");
element.parentNode.removeChild(element);
}
For some reason when I click the close button nothing happens. If anyone could point me in the right direction that would be awesome.
you can assign a click handler to a dom element like this: element.onclick = callback; where callback is your callback function.
This works as expected:
function close(){
var element = document.getElementById("buy-ticket");
element.parentNode.removeChild(element);
}
var o = document.createElement('div');
o.className = 'overlay';
var p = document.createElement('div');
p.className = 'buyticketid';
p.setAttribute('id','buy-ticket');
var cb = document.createElement('p');
cb.className = 'closeButton';
cb.onclick = close;
cb.setAttribute('title','Close');
cb.setAttribute('id','close-btn');
var x = document.createTextNode('x');
cb.appendChild(x);
p.appendChild(cb);
document.getElementsByTagName('body')[0].appendChild(o);
document.getElementsByTagName('body')[0].appendChild(p);

Remove clicked <li> onclick

I have this JavaScript code:
window.onload = init;
function init () {
var button = document.getElementById("submitButton");
button.onclick = addItem;
var listItems = document.querySelectorAll("li"); //assigning the remove click event to all list items
for (var i = 0; i < listItems.length; i++) {
listItems[i].onclick = li.parentNode.removeChild(li);
}
}
function addItem() {
var textInput = document.getElementById("item"); //getting text input
var text = textInput.value; //getting value of text input element
var ul = document.getElementById("ul"); //getting element <ul> to add element to
var li = document.createElement("li"); //creating li element to add
li.innerHTML = text; //inserting text into newly created <li> element
if (ul.childElementCount == 0) { //using if/else statement to add items to top of list
ul.appendChild(li); // will add if count of ul children is 0 otherwise add before first item
}
else {
ul.insertBefore(li, ul.firstChild);
}
}
function remove(e) {
var li = e.target;
var listItems = document.querySelectorAll("li");
var ul = document.getElementById("ul");
li.parentNode.removeChild(li);
}
and this HTML:
<body>
<form>
<label for="item">Add an item: </label>
<input id="item" type="text" size="20"><br>
<input id="submitButton" type="button" value="Add!">
</form>
<ul id="ul">
</ul>
<p>
Click an item to remove it from the list.
</p>
</body>
What I want to do is remove the whichever <li> element the user clicks, but this doesn't seem to be working and I am unable to find an answer anywhere else online for this specific scenario. Hoping someone can help me out here and show me what i am missing.
UPDATE
Plain JS delegation
Add the eventListener to the UL to delegate the click even on dynamically inserted LIs:
document.getElementById("ul").addEventListener("click",function(e) {
var tgt = e.target;
if (tgt.tagName.toUpperCase() == "LI") {
tgt.parentNode.removeChild(tgt); // or tgt.remove();
}
});
jQuery delegation
$(function() {
$("#submitButton").on("click",function() {
var text = $("#item").val(); //getting value of text input element
var li = $('<li/>').text(text)
$("#ul").prepend(li);
});
$("#ul").on("click","li",function() {
$(this).remove();
});
});
Original answer
Since you did not mention jQuery
var listItems = document.getElementsByTagName("li"); // or document.querySelectorAll("li");
for (var i = 0; i < listItems.length; i++) {
listItems[i].onclick = function() {this.parentNode.removeChild(this);}
}
you may want to wrap that in
window.onload=function() { // or addEventListener
// do stuff to the DOM here
}
Re-reading the question I think you also want to add that to the dynamic LIs
li.innerHTML = text; //inserting text into newly created <li> element
li.onclick = function() {
this.parentNode.removeChild(this);
// or this.remove(); if supported
}
Here is the complete code as I expect you meant to code it
Live Demo
window.onload=function() {
var button = document.getElementById("submitButton");
button.onclick = addItem;
}
function addItem() {
var textInput = document.getElementById("item"); //getting text input
var text = textInput.value; //getting value of text input element
var ul = document.getElementById("ul"); //getting element <ul> to add element to
var li = document.createElement("li"); //creating li element to add
li.innerHTML = text; //inserting text into newly created <li> element
li.onclick = function() {
this.parentNode.removeChild(this);
// or this.remove(); if supported
}
if (ul.childElementCount == 0) { //using if/else statement to add items to top of list
ul.appendChild(li); // will add if count of ul children is 0 otherwise add before first item
}
else {
ul.insertBefore(li, ul.firstChild);
}
}
In case you want to use jQuery, the whole thing gets somewhat simpler
Live Demo
$(function() {
$("#submitButton").on("click",function() {
var text = $("#item").val(); //getting value of text input element
var li = $('<li/>')
.text(text)
.on("click",function() { $(this).remove()});
$("#ul").prepend(li);
});
});
I know you already received an answer, but back to your original remove function. You have the following:
function remove(e) {
var li = e.target;
var listItems = document.querySelectorAll("li");
var ul = document.getElementById("ul");
li.parentNode.removeChild(li);
}
Change it to this and you should get what you were trying to achieve:
function remove(e)
{
var li = e.target;
var ol = li.parentElement;
ol.removeChild( li);
return false;
}
I'd suggest simplifying things a little:
Object.prototype.remove = function(){
this.parentNode.removeChild(this);
};
var lis = document.querySelectorAll('li');
for (var i = 0, len = lis.length; i < len; i++) {
lis[i].addEventListener('click', remove, false);
}
JS Fiddle demo.
Of course, having done the above, I'd then have to go further (possibly because I like jQuery too much) and also:
Object.prototype.on = function (evt, fn) {
var self = this.length ? this : [this];
for (var i = 0, len = self.length; i < len; i++){
self[i].addEventListener(evt, fn, false);
}
};
Object.prototype.remove = function(){
var self = this.length ? this : [this];
for (var i = 0, len = self.length; i < len; i++){
self[i].parentNode.removeChild(self[i]);
}
};
document.querySelectorAll('li').on('click', remove);
JS Fiddle demo.
If you don't want to write function in javascript, you can use immediately invoked anonymous function like below...
<elem onclick="(function(_this){_this.parentNode.removeChild(_this);})(this);"
If I understood you correctly:
$("li").on("click", function() {
$(this).remove()
});
The answer is more obvious than it could seem, you forgot to add init() in your script, is normal that the click event aren't triggered, they're not set on the element!
EDIT:
Your code has some logical errors. If you don't add an onclick function for all those created elements you will not be able to remove the clicked element. This is because the function init() is called one time at the load of the page!
function init() {
var button = document.getElementById("submitButton");
button.onclick = function() {addItem()};
}
function addItem() {
var textInput = document.getElementById("item"); //getting text input
var text = textInput.value; //getting value of text input element
var ul = document.getElementById("ul"); //getting element <ul> to add element to
var li = document.createElement("li"); //creating li element to add
li.innerHTML = text; //inserting text into newly created <li> element
li.onclick = function() {this.parentNode.removeChild(this);}
if (ul.childElementCount == 0) { //using if/else statement to add items to top of list
ul.appendChild(li); // will add if count of ul children is 0 otherwise add before first item
} else {
ul.insertBefore(li, ul.firstChild);
}
}
init();

Categories

Resources