How to run a nested javascript function? - javascript

I am new to object orientated programming in javascript and am trying to understand some functions in a project I am working on.
How would I call/run the internal function (the one listed 'this.getFieldset = function() {') to execute?
function Fieldset() {
this.id = "";
this.content = document.createElement("DIV");
this.content.id = "content";
this.title = "Title";
this.getFieldset = function() {
var div = document.createElement("DIV");
div.id = this.id;
var span = document.createElement("SPAN");
var fieldset = document.createElement("DIV");
fieldset.id = "fieldset";
var header = document.createElement("DIV");
header.id = "header";
span.appendChild(document.createTextNode(this.title));
header.appendChild(span);
div.appendChild(header);
div.appendChild(this.content);
div.appendChild(fieldset);
return div;
}
}
var myFieldset = new Fieldset();
myFieldset.getFieldset();

First you should create an instance of Fieldset, then you'll be able to call its functions (called methods):
var myFieldset = new Fieldset();
myFieldset.getFieldset();

function Fieldset() {
this.id = "";
this.content = document.createElement("DIV");
this.content.id = "content";
this.title = "Title";
this.getFieldset = function() {
var div = document.createElement("DIV");
div.id = this.id;
var span = document.createElement("SPAN");
//var fieldset = document.createElement("DIV");
//fieldset.id = "fieldset";
var header = document.createElement("DIV");
header.id = "header";
span.appendChild(document.createTextNode(this.title));
header.appendChild(span);
div.appendChild(header);
div.appendChild(this.content);
div.appendChild(fieldset);
window.alert("test");
return div;
}
//add call to run function
this.getFieldset();
}

Related

How can I create a div and set a class attribute in angular?

I have this code and it works with javascript, I want to create a div and a class, how can I do the same with angular?
buildPhotoStruct() {
var rowContainer = document.getElementById("row-container");
var photoContainer = document.createElement("div");
photoContainer.className = "photo-container";
var photoDiv = document.createElement("div");
photoDiv.className = "photo";
var img = document.createElement('img');
img.src = '../../assets/img/leopard.jpg';
var button = document.createElement('button');
photoDiv.appendChild(img);
photoContainer.appendChild(photoDiv);
photoContainer.appendChild(button);
rowContainer.appendChild(photoContainer);
}

Javascript function not looping properly over items

This is my JS that adds evenet listeners to every ideanode:
var ideanodes = [...document.querySelectorAll('.ideanode')];
ideaNodesListRefresh();
function ideaNodesListRefresh(){
ideanodes = [...document.querySelectorAll('.ideanode')];
console.log("refreshed")
ideanodes.forEach(ideanode => {
var maintxt = ideanode.querySelector(".maintext");
var titleArrow = ideanode.querySelector(".title-arrow");
var mainArrow = ideanode.querySelector(".maintxt-arrow");
var comments = ideanode.querySelector(".comments");
titleArrow.addEventListener('click', function() {
maintxt.classList.toggle("hidden");
mainArrow.classList.toggle("hidden");
if (comments.classList.contains("hidden")) {;
} else {
comments.classList.toggle("hidden");
};
});
mainArrow.addEventListener("click", function() {
comments.classList.toggle("hidden");
});
});
};
the function gets fired at the end of the creation of a new ideanode:
function createNeed(user) {
if (user==user1) {
var newNeed = document.createElement('div');
newNeed.className = "ideanode";
var newNeedHeader = document.createElement('div');
newNeedHeader.className = "ideanodeheader";
var newNeedHeaderText = document.createTextNode('Need');
newNeedHeader.appendChild(newNeedHeaderText);
newNeed.appendChild(newNeedHeader);
var newNeedContent = document.createElement('div');
newNeedContent.className = "content";
newNeed.appendChild(newNeedContent);
var needTitle = document.createElement('div');
needTitle.className="title";
var needTitleH3 = document.createElement('h2');
var titleText = document.createTextNode('Title');
needTitleH3.appendChild(titleText);
needTitleH3.setAttribute('onclick', 'this.focus();');
needTitleH3.setAttribute('contenteditable', 'True');
newNeedContent.appendChild(needTitleH3);
var downArrow0 = document.createElement('i');
downArrow0.classList = 'fas fa-sort-down title-arrow';
newNeedContent.appendChild(downArrow0);
var maintext = document.createElement('div');
maintext.classList = 'maintext hidden';
textareaMain = document.createElement("textarea");
textareaMain.className = "maintextinput";
textareaMain.setAttribute('placeholder', 'Text');
maintext.appendChild(textareaMain);
newNeedContent.appendChild(maintext);
var downArrow1 = document.createElement('i');
downArrow1.classList = 'fas fa-sort-down maintxt-arrow hidden';
newNeedContent.appendChild(downArrow1);
var comments = document.createElement('div');
comments.classList = "comments hidden";
textareaComments = document.createElement("textarea");
textareaComments.className = "commentsinput";
textareaComments.setAttribute('placeholder', 'Comments');
comments.appendChild(textareaComments);
newNeedContent.appendChild(comments);
newNeed.appendChild(newNeedContent);
var container = document.querySelector('#needsuser1');
var lastNeed = document.querySelector(".ideanode:last-child");
lastNeed.parentNode.insertBefore(newNeed, lastNeed.nextSibling);
ideaNodesListRefresh();
} else {
console.log("user2")
}
}
But when I add a new ideanode the function doesn't work properly and the eventlisteners only work for the newest ideanode.
This is a codepen of what I'm doing: https://codepen.io/ricodon1000/pen/PoPeXJL
I would like to simply add eventlisteners to the arrows of the new ideanode and have all of the arrows of all of the ideanodes work.

Access parent object property of image element

I have a list of cats. Each cat object has a property cat.clicks that record the number of times the cat image has been clicked. The cat image's onclick calls the method cat.clickCat.
But of course 'this' in the clickCat method refers to the image element and not the cat object which contains the property 'clicks'.
How do I display and update the number of clicks on the image?
function Cat(src, name) {
this.src = src;
this.name = name;
this.clicks = 0; //property recording no. of clicks
}
Cat.prototype.createCatItem = function() {
let catDisplay = document.createElement("div");
catDisplay.id = "catDisplay"
let catName = document.createElement("h2");
let catImg = document.createElement("img");
let catCounter = document.createElement("div");
catCounter.id = "clicker";
catName.innerHTML = this.name;
catImg.src = this.src;
catImg.onclick = this.clickCat; //call the clickCat method
catDisplay.appendChild(catName);
catDisplay.appendChild(catImg);
catDisplay.appendChild(catCounter);
return catDisplay;
}
Cat.prototype.clickCat = function() {
this.clicks += 1; //how to access the object property clicks from this method?
let clickerDiv = document.getElementById("clicker")
clickerDiv.innerHTML = ''
clickerDiv.innerHTML = 'clicks = ' + this.clicks;
}
function App() {
this.cats = [];
}
App.prototype.add = function(cat) {
this.cats.push(cat)
}
App.prototype.listCats = function() {
let container = document.getElementById("container");
let ul = document.createElement("ul");
for (let i=0; i<this.cats.length; i++){
let li = document.createElement("li");
li.innerHTML = this.cats[i].name;
li.onclick = this.displayCat;
ul.appendChild(li);
}
container.appendChild(ul);
}
App.prototype.displayCat = function() {
let container = document.getElementById("container");
let catDisplay = document.getElementById("catDisplay")
let cats = app.cats;
let chosenCat = cats.filter(cat => cat.name === this.innerHTML);
let chosenCatItem = chosenCat[0].createCatItem();
container.removeChild(catDisplay);
container.appendChild(chosenCatItem);
console.log(chosenCat);
}
App.prototype.showFirstCat = function() {
let container = document.getElementById("container");
let catDisplay = document.getElementById("catDisplay")
let firstCat = app.cats[0].createCatItem();
container.appendChild(firstCat);
}
let app = new App;
let tea = new Cat("http://placehold.it/350x150", "tea");
let snowball = new Cat("http://placehold.it/350x200", "snowball");
let triksy = new Cat("http://placehold.it/350x300", "triksy");
let vera = new Cat("http://placehold.it/350x350", "vera");
let jon = new Cat("http://placehold.it/350x400", "jon");
app.add(tea)
app.add(snowball)
app.add(triksy)
app.add(vera)
app.add(jon)
app.listCats();
app.showFirstCat();
<div id="container">
<h1>My Cat Clicker</h1>
</div>
First of all .. beware of using this ... this always refer the object currently responsible to execute the scripts in browser ... so in your case the image is responsible for executing the click event and it has no property called clicks .. and that's why clicks is NaN
A good practice is preserve this into a variable to avoid the system replacement when executing (that=this)
Cat.prototype.createCatItem = function() {
let that=this; //preserving this value
let catDisplay = document.createElement("div");
catDisplay.id = "catDisplay"
let catName = document.createElement("h2");
let catImg = document.createElement("img");
let catCounter = document.createElement("div");
catCounter.id = "clicker";
catName.innerHTML = this.name;
catImg.src = this.src;
catImg.onclick = function() {
//alert(this);
that.clicks += 1; //how to access the object property clicks from this method?
let clickerDiv = document.getElementById("clicker")
clickerDiv.innerHTML = ''
clickerDiv.innerHTML = 'clicks = ' + that.clicks;
}
catDisplay.appendChild(catName);
catDisplay.appendChild(catImg);
catDisplay.appendChild(catCounter);
return catDisplay;
}
//Cat.prototype.clickCat = function() {
// this.clicks += 1; //how to access the object property clicks from this method?
// let clickerDiv = document.getElementById("clicker")
// clickerDiv.innerHTML = ''
// clickerDiv.innerHTML = 'clicks = ' + this.clicks;
//}

How to add an Id, value and onclick event to a dynamic generated div

i have to add onglets (dev) and affect them an id, value and onclick.
i tried by this way but is not working
function functionDeleteLevel(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
var formData = new FormData();
formData.append("valeur", "deleteLevel");
ajaxPost("/deleteLevel", formData, function (reponse) {
var data = JSON.parse(reponse);
data.forEach(function(level){
var newLi = document.createElement("li");
newLi.value = level.level;
newLi.id = "levelId_"+level.level;
newLi.innerHTML = 'onclick="functionSelectedLevel(this.id)"';
newLi.innerHTML = '<a data-toggle="tab">Niveau'+level.level+'</a>';
s2.appendChild(newLi);
});
});
}
you can use
newLi.addEventListener('click', function() {functionSelectedLevel(this.id);})
or
newLi.onclick = function() {functionSelectedLevel(this.id);};
or - with a bit of a change to functionSelectedLevel
newLi.addEventListener('click', functionSelectedLevel)
or
newLi.onclick = functionSelectedLevel;
functionSelectedLevel would then be
functionSelectedLevel() {
// here, the value of this is the element that was clicked
do things with this.id
}

Creating dynamic div using javascript

<script>
function selecteditems()
{
var i=1;
var val="";
while(i<=53)
{
if(document.getElementById('timedrpact'+i)!="")
{
val+=document.getElementById('timedrpact'+i).value;
document.getElementById('showselecteditems').innerHTML=val;
}
i++;
}
}
</script>
How to create a new div and add contents to it?In the above case i lost previous content due to innerHTML.I want new div each time for dynamically attach an image and the above variable val to it.
Thanks in advance.
Check this Demo
<div id="output" class="out">
</div>
window.onload=function(){
var output = document.getElementById('output');
var i=1;
var val="";
while(i<=3)
{
if(!document.getElementById('timedrpact'+i))
{
var ele = document.createElement("div");
ele.setAttribute("id","timedrpact"+i);
ele.setAttribute("class","inner");
ele.innerHTML="hi "+i;
output.appendChild(ele);
}
i++;
}
};
Look at document.createElement() and element.appendChild().
var newdiv = document.createElement("div");
newdiv.innerHTML = val;
document.getElementById("showselecteditems").appendChild(newdiv);
Because you will likely encounter this in the near future: You can remove any element with this code:
element.parentNode.removeChild(element);
Using createElement:
function selecteditems() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=53;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(fld.value));
container.appendChild(div);
}
}
}
Full version using cloneNode (faster) and eventBubbling
Live Demo
var div = document.createElement("div");
var lnk = document.createElement("a");
var img = document.createElement("img")
img.className="remove";
img.src = "https://uperform.sc.gov/ucontent/e14c3ba6e4e34d5e95953e6d16c30352_en-US/wi/xhtml/static/noteicon_7.png";
lnk.appendChild(img);
div.appendChild(lnk);
function getInputs() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=5;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var newDiv = div.cloneNode(true);
newDiv.getElementsByTagName("a")[0].appendChild(document.createTextNode(fld.value));
container.appendChild(newDiv);
}
}
}
window.onload=function() {
document.getElementById('showselecteditems').onclick = function(e) {
e=e||event;
var target = e.target||e.srcElement;
// target is the element that has been clicked
if (target && target.className=='remove') {
parentDiv = target.parentNode.parentNode;
parentDiv.parentNode.removeChild(parentDiv);
return false; // stop event from bubbling elsewhere
}
}
getInputs();
}
Syntax for dynamic create div:
DivId = document.createElement('div');
DivId.innerHtml ="text"

Categories

Resources