issue refreshing div with Javascript - javascript

I am trying to write some code that upon clicking on a button, a div is populated as seen in the code below. The problem is that I want to ensure that if the button is clicked multiple times, that the div reloads so to speak. I tried implementing this with the refreshDiv function below, but with this included the action of clicking the button does nothing.
function buttonClickHandler() {
var divString = "foodJournal";
refreshDiv(divString);
var divID = document.getElementById("foodJournal");
var fieldset = document.createElement("fieldset");
var legend = document.createElement("legend");
legend.innerHTML = "Food Log";
legend.setAttribute('id', "legend");
divID.appendChild(fieldset);
fieldset.appendChild(legend);
//refreshes food journal div
var refreshDiv = function(element) {
node = document.getElementById(element);
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
};
}
Any help is appreciated!

You are making a call to refreshDiv before actually declaring the variable. Move the variable declaration above the call to it and it should work.
function buttonClickHandler() {
var divString = "foodJournal";
//refreshes food journal div
var refreshDiv = function(element) {
node = document.getElementById(element);
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
};
refreshDiv(divString);
var divID = document.getElementById("foodJournal");
var fieldset = document.createElement("fieldset");
var legend = document.createElement("legend");
legend.innerHTML = "Food Log";
legend.setAttribute('id', "legend");
divID.appendChild(fieldset);
fieldset.appendChild(legend);
}

The code, as you have it written will result in an error in the console. On Chrome, you would see:
Uncaught TypeError: undefined is not a function
pointing right at the first refreshDiv(divString) statement.
While variables are hoisted in javascript, only the declaration is hoisted, not the assignment. (see fiddle with error)
A simple fix would be to move both the variable declaration and its assignment above the first call to refreshDiv. (Simple fix example)
function buttonClickHandler() {
var divString = "foodJournal";
//refreshes food journal div
var refreshDiv = function(element) {
node = document.getElementById(element);
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
};
refreshDiv(divString);
var divID = document.getElementById("foodJournal");
var fieldset = document.createElement("fieldset");
var legend = document.createElement("legend");
legend.innerHTML = "Food Log";
legend.setAttribute('id', "legend");
divID.appendChild(fieldset);
fieldset.appendChild(legend);
}
As written in your sample, there really is no reason to have a separate method to clear the div. If this wasn't just to illustrate the problem you were having, you might consider refactoring the code a bit to reduce some of the redundancy and remove the unnecessary function call.

Related

Making a comment to the DOM from a constructor function

I am trying to make function that will post comment that'll add a headline and a text-section, based on a constructor-object. #Title and #text are the two bars in which the text will go. #form is the button the event listens to. I can't seem to get it to work now. Ideas?
function commentPost (title, text){
this.title = $("title").val;
this.tekst = $("text").val;
}
var commentPosts = [];
var formular = $('#form');
formular.on('click', function getTarget(e) {
e.preventDefault();
var jsTitleInput = $('title').val;
var jsTextInput = $('text').val;
var newComment = new commentPost(jsTitleInput, jsTextInput);
commentPost.push(newComment);
console.log(newComment);
});

How To Create And Assign And Onclick Element To Another Element Created In JS

So, I am trying to make an element and then assign an onclick to it through JS.
Here is my code so far:
HTML
<div id = "Programs" onclick = "Cpb()">Programs</div>
JS
function Cpb() {
document.getElementById("AllBody").innerHTML = "";
var rh = document.createElement("h2");
var rht = document.createTextNode("Recent Programs");
rh.id = "Recentt";
var rh1 = document.createElement("h4");
var rh1t = document.createTextNode("test");
rh1t.onclick = window.open('website');
rh1.appendChild(rh1t);
rh.appendChild(rht);
}
So does anybody know how I can do this?
This javascript worked for me:
let h4Node = document.createElement("H4");
h4Node.innerHTML = "4th Header";
h4Node.onclick = function (){
alert('Oi!');
};
document.getElementById("demo").appendChild(h4Node);
Html:
<div class="demo"></div>
It will put an h4 element with an onclick event listener inside the demo div.
I think you want addEventListener.
Example:
rh1t.addEventListener('click', myHandlerFunction);
function myHandlerFunction () {
// ...
}
You can continue using onclick as you have in your code. But you'll need to do as I've done above and assign a function reference to it. Like this:
rh1t.onclick = myHandlerFunction;
function myHandlerFunction () {
window.open('website');
}

Assigning an event function to many elements with pure Javascript

I'm building a table of links containing images with a javascript function. Here's the code:
function populateGrid(dataArray) {
var table = document.createElement("table");
table.id = "data-table";
var row = document.createElement("tr");
for (var i = 1; i <= dataArray.length; i++) {
var tableItem = document.createElement("td");
var linkContainer = document.createElement("a");
var itemImage = document.createElement("img");
linkContainer.href = dataArray[i - 1].url;
linkContainer.target = "_blank";
itemImage.onmouseover = function(e) {
linkHover(e);
};
itemImage.onmouseout = function(e) {
linkBlur(e);
};
itemImage.src = dataArray[i - 1].logo;
linkContainer.appendChild(itemImage);
tableItem.appendChild(linkContainer);
row.appendChild(tableItem);
// This checks to see if it's time to make a new row, in order to keep the table a square
if (i % Math.round(Math.sqrt(dataArray.length + 1)) === 0) {
table.appendChild(row);
row = document.createElement("tr");
}
}
table.appendChild(row);
document.getElementById('inject').appendChild(table);
}
I'm having issues with assigning the "onmouseover" and "onmouseout" events to each individual table item. Lint is telling me that it's bad form to assign functions within a for-loop, and it definitely seems messy to me. I've tried this:
itemImage.onmouseover = linkHover(e);
But when I do it this way, I get the error: "Uncaught ReferenceError: e is not defined". I need some context as to which element is causing the linkHover and linkBlur functions to be called, as I change the border of the corresponding image as seen in this .gif:
(I don't have enough reputation to post images, so here's the link: http://i.imgur.com/6r8rQQp.gifv)
My linkHover and linkBlur functions are as follows:
function linkHover(e) {
e.target.className = "green-border";
}
function linkBlur(e) {
e.target.className = "";
}
My question is: how should I do this better? I'm sure there must be a cleaner way that doesn't give lint errors.
Thanks in advance for your help.
EDIT:
Okay, so following gcampbell's advice, I'm assigning the event listener to the table like so:
var table = document.createElement("table");
table.onmouseover = function(e) {
linkHover(e);
};
table.onmouseout = function(e) {
linkBlur(e);
};
And then I check to make sure the target was an img:
function linkHover(e) {
if (e.target.tagName == "IMG") {
e.target.className = "green-border";
}
}
Is this bad form? Should I just condense these functions into the event assignments?
Thanks.

Javascript: Get the innerHTML of a dynamically created div

I am retrieving some information from an xml file ( movie information ) and I am creating dynamically some DOM elements according to each movie. I want, when I click on the test element, to get the value of the title of the movie. Right now, no matter which movie I click, it gets the title of the last movie that was introduced.
How can I get the title of each individual movie when I click on that div and not the last one introduced by the for-loop?
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("movie");
for (i=0;i<x.length;i++)
{
var titlu = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
var description = x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
var descriere = document.createElement('div');
descriere.className='expandedDescriere';
descriere.innerHTML = description;
var titlediv = document.createElement('div');
titlediv.className = 'title';
titlediv.id='title';
titlediv.innerHTML = title;
var test=document.createElement('div');
test.className='test';
test.onclick= function(){
var filmName= test.previousSibling.innerHTML;
alert(filmName);
}
placeholder.appendChild(titlediv);
placeholder.appendChild(test);
placeholder.appendChild(descriere);
}
I think your problem might be in the function you assigned to onclick:
test.onclick= function(){
var filmName= test.previousSibling.innerHTML; // <===
alert(filmName);
}
the marked line should be var filmName= this.previousSibling.innerHTML;
My guess is that the var test is hoisted out of the for loop, meaning that when the loop finished, all the onclick function are referencing the same test variable which is the last element you created.
Use this to reference the clicked element:
test.onclick = function() {
var filmName = this.previousSibling.innerHTML;
alert(filmName);
};

Cannot remove a div in 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...

Categories

Resources