Cannot remove a div in Javascript - javascript

I'm trying to remove a div in Javascript but 'its not working. I get no error in my console yet the function does get called.
I don't understand what I have done wrong, so I'm hoping someone can explain. This is how it works:
function menu_load(type){
document.getElementById(type).onclick = function(){ menu_unload(type); }
var width = 100;
var height = 100;
var d = document.createElement('div');
d.id = 'menu';
d.className = 'menu';
d.style.width = width + 'px';
d.style.height = height + 'px';
document.getElementById('G').appendChild(d);
}
function menu_unload(type){
alert('test'); //this displays
var div = document.getElementById("menu");
div.parentNode.removeChild(div); // doesn't remove the div
document.getElementById(type).onclick = menu_load(type);
}
window.onload = function(){
menu_load('test');
}
Is there any mistake here that I have missed? I just can't work out the problem.

Your code works for me if I correct the following line:
document.getElementById(type).onclick = menu_load(type);
Which incorrectly calls menu_load() and tries to assign the result to .onclick. It should be like you did in the other function
document.getElementById(type).onclick = function() { menu_load(type); };
Demo: http://jsfiddle.net/MCZza/
To be honest I don't know why this fixes it, since your code wasn't actually a syntax error, but because it called menu_load() it recreated the div just removed. and the .removeChild() line should happen first, but anyway...

Related

How to pass a variable in document.getElementById. As well as getting undefined when calling a value in an array

<iframe id="frmFile" src="Book1.txt" onload="generateInventory();" style="display: none;"></iframe>
<script>
function csvpls() {
var oFrame = document.getElementById("frmFile");
var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
while (strRawContents.indexOf("\r") >= 0)
strRawContents = strRawContents.replace("\r", "");
var arrLines = strRawContents.split(",");
return arrLines
}
function generateInventory(a, b) {
var xx = csvpls()
var div = document.createElement("div");
div.style.width = "1000px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello " + xx[a] + " yes!";
document.getElementById(b).appendChild(div);
}
</script>
<div id="Q1"></div>
<script>
generateInventory(20, Q1);</script>
</body>
I am trying to create edit multiple divs with the following code. I hope to call each function with parameters to create the divs and put content in them.
So I have some problems with the code above. First off, document.getElementById(str).appendChild(div); is not working the way I want it to. It works if I put the div id "Q1" instead of b. Just wondering, if I can pass a variable through it. Secondly, when I change the div to "Q1", the div is generated, but the content in there is "Hello undefined Yes". If I call the array with xx[20] instead of xx[a], I would get what I want which is "Hello content yes". Sorry, this probably seems like a nuisance, any help is appreciated.

Setting onclick function dynamically in Javascript not working

hello =) I am trying to create a heading tag with some text in it.
var d = document.createElement("h5");
d.innerHTML = "Dungeon";
and then assigning an onclick listener.
d.onclick = function(){myFunction()};
which doesn't seem to be working. I've also tried
d.onmousedown = function(){myFunction();};
and
d.onclick = "myFunction()";
and
d.addEventListener("mousedown", function(){myFunction});
and none of them seem to be working. I have thrown in a couple tracers around it, everything runs through fine without syntax errors but the actual element when appended to the document doesn't have the function tied to it at all. Would anyone happen to know why? Thanks in advance =)
Edit:
Here is a more detailed block of my code. Would this make any difference?
var x = document.createElement("ul");
var y = document.createElement("li");
x.appendChild(y);
var d = document.createElement("h5");
d.innerHTML = "Dungeon";
y.appendChild(d);
console.log(0);
d.onclick = function() { alert('test'); }
console.log(1);
elem.addEventListener("click", function, false);

mouseenter works, mouseleave does not

Having trouble with my mouseenter and mouseleave. Ive looked up examples on stack and yt but haven't found anything useful. Im assuming I have to make two functions or maybe just refactor into one. Either way any help is appreciated. I have already declared in the html element itself the height and width at 50px. If you need me to be more specific cool. Im not a professional at javascript so don't get upset that I didn't notice something. If i did just explain to me so i know for future reference. Thanks!
var modWidth;
$('#icons a img').on('mouseenter', function(){
$(this).width(modWidth);
$(this).height(modWidth);
var modWidth = 75;
});
$('#icons a img').on('mouseleave', function(){
$(this).width(modWidth);
$(this).height(modWidth);
var modWidth = 50;
});
You only need to declare modWidth once, other then that you will need to set a number to modWidth before using it, see fiddle https://jsfiddle.net/kvb5hb6f/1/
var modWidth;
$('#demo').on('mouseenter', function() {
modWidth = 75;
$(this).width(modWidth);
$(this).height(modWidth);
});
$('#demo').on('mouseleave', function() {
modWidth = 50;
$(this).width(modWidth);
$(this).height(modWidth);
});
The problem is that you're shadowing the modWidth variable by creating a new one inside of each function. For example:
var myName = 'Mike';
function bob() {
var myName = 'Bob';
console.log('My name is ' + myName);
}
bob();
// Notice that `bob` does not overwrite the original `myName`
// It created a new `myName` in it's own scope
console.log('My name is ' + myName);
To avoid that, only declare modWidth once.
var modWidth;
$('#icons a img').on('mouseenter', function() {
$(this).width(modWidth);
$(this).height(modWidth);
modWidth = 50; // Notice that I removed `var`
});
$('#icons a img').on('mouseleave', function() {
$(this).width(modWidth);
$(this).height(modWidth);
modWidth = 75; // Notice that I removed `var`
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="icons">
<a href="#">
<img src="https://placehold.it/50x50">
</a>
</div>

get property (width) from one element and assign to another one

I am trying to get the width property from one element and assign to another.
Here's my code (that does not work):
window.onload=function() {
var morphWidth = document.getElementById('morph').width();
var scrollbar = document.getElementById('scrollbar');
scrollbar.style.width = morphWidth + "px";
}
You can get the element width:
document.getElementById("morp").style.width;
and you can set the element width:
document.getElementById("morph").style.width="300px";
Okay, so I tried this and that and finally found a solution:
$(function() {
var morphWidth = $('#morph').width();
var scrollbar = $('#scrollbar');
$('#scrollbar').css('width', morphWidth + 'px');
});
However, I don't have a clue why this works now. Let me know if you do!
If you use jQuery, then you can code like this:
var morphWidth = $('#morph').width();
If you use original Javascript, the you can code like this:
var morphWidth = document.getElementById('morph').offsetWidth;
jQuery object is different from DOM (Document Object Model).
The var scrollbar as same as.

Javascript Create Clickable Text

EDIT 2 - I decided to create a simple example with jsfiddle.
http://jsfiddle.net/VqA9g/61/
As you can see, I am trying to reference the new div.
EDIT - d/t negative votes and unclear question
I have a linked-list like so:
var struct_list = function () {
this.id = 0;
this.name = 0;
this._head = null;
};
struct_list.prototype = {
// .. adding code , delete code ...
list_contents: function () {
var current = this._head;
while ( current != null ) {
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "white";
div.style.color = "black";
div.style.top = "0px";
div.style.left = "0px";
div.style.margin = "400px 1000px auto";
div.style.cursor = "pointer";
div.innerHTML = current.name;
div.onclick = function ( v ) { var d = document.getElementById('div'); alert(d)};
document.body.appendChild(div);
current = current.next;
}
return null;
},};
I want to be able to display this linked list, and each item displayed be able to interact with an "onclick".
Example:
struct_list.add ( 0 , "Zero" );
struct_list.add ( 1 , "One" );
struct_list.list_contents();
_________________________________________________________________________
| |
| <clickable> "Zero" that does a function(id) that passes over its ID(0) |
|________________________________________________________________________|
| |
| <clickable> "One" <same as above> |
|________________________________________________________________________|
Sorry if I was unclear. Will reedit if still unclear. My apologies.
I have a linked-list struct that I hold data in (it changes data frequently) and I have a setInterval to refresh it. My question is how can I list the struct's contents while still being able to click the exposed content, I have it set up right now that each content in the linked-list contains an id. Also , how can I make sure that overflow is automatic for the y axis? I am guessing I have to place it into a div that has that enabled.
But my real question is how to expose the linked-lists elements while also being able to interact with them via an onclick.
I also do not want to use anything other than pure javascript.
Example (in my mind) would maybe be something like:
<div id="PopUp">
<script>
setInterval(function() {
if ( struct_qued_list ) {
struct_qued_list = false;
main.struct_list.list_contents(); // the linked list
}
}, 100);
</script>
</div>
list_contents: function () {
var current = this._head;
while ( current != null ) {
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "white";
div.style.color = "black";
div.style.top = "0px";
div.style.left = "0px";
div.style.margin = "400px 1000px auto";
div.style.cursor = "pointer";
div.innerHTML = current.name;
div.onclick = function ( v ) { var d = document.getElementById('div'); alert(d)};
document.body.appendChild(div);
current = current.next;
}
return null;
},
Any help or logical way to do this would be appreciated.
This is mainly a scope problem, in your Edit 2 fiddle, the alert gives undefined because your i got the value 2 in order to leave the loop.
Here is a possible solution : Live demo (jsfiddle)
!function(){
var index = i; // Make it independant of i
div.onclick = function () { alert(list[index]); };
}();
You could also use attributes to store any value, and using this in the function to retrieve it.
Or export the whole process to another function to obtain something like this :
for ( var i = 0; i < 2 ; i++ ) {
doSomething(i);
}
When you add new content to the DOM JavaScript sometimes has a hard time picking that up. You may need to use a DOM mutation event (like DOMNodeInserted) to add the event listeners to your text nodes.
document.addEventListener('DOMNodeInserted', function(){
document.getElementById('thing').addEventListener('click', function(){
alert('yey!');
});
});
you may need to name your functions so you can remove them as well, if nodes are going to be inserted without removing all the old ones. Yes this is pure javascript.
EDIT: for your overflow issue, you could assign a class to each node as you insert it and style the class via CSS
.classname {
overflow: auto;
}

Categories

Resources