create multiple elements (list) with onclick event - javascript

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);
});
};

Related

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

How to pass parameters permanently javascript function

How would I make this function work so that whenever the element I created is clicked it uses the parameters from the function in the actual click event.
function createLink(text, parentElement) {
var a = document.createElement('p');
var linkText = document.createTextNode(text);
a.appendChild(linkText);
temp1 = text.replace("/","-");
temp2 = res1.replace("/","-");
a.onClick = goSpecificPrev(temp2,linkText);
parentElement.appendChild(a);
var br = document.createElement('br');
parentElement.appendChild(br);
}
The parameters in questions are in the line:
a.onClick = goSpecificPrev(temp2,linkText);
being temp2 and linkText.

Uncaught TypeError: Cannot set property 'onfocus' of null

I am trying to learn JavaScript and I'm building this basic tutorial. In trying to demonstrate onfocus and onblur, I get this error message in my JavaScript console: Uncaught TypeError: cannot set property 'onfocus' of null.
Here is my code. I am new to learning JavaScript and could really use some help.
//alert("Hello, world!");
// this is a JavaScript alert button
//
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;
if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */
var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);
var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);
var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);
var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);
var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);
// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");
// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro to JavaScript! YAY!");
newPara.appendChild(paraText);
//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);
var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);
// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
// alert("You clicked somewhere in the document");
//}
// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
emailField.value = "";
}
};
emailField.onblur = function() {
if (emailField.value == "") {
emailField.value = "your email";
}
};
}
window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers(); // This is a named function call nested inside an anonymous function.
}
//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds
var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White-Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;
function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setInterval(changeImage, 5000);
//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */
/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */
If it's giving you that error, then it means that document.getElementById("email") evaluates to null, which means that no element exists with the id email.
That's all I can tell you without seeing the HTML that this JS is connected to.

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

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.

Passing a javascript value

I want to pass a numeric value through to the following Javascript function.
function swap2() {
var oldDiv = document.getElementById("product-grid");
var newDiv = document.getElementById("product-page");
oldDiv.style.display = "none";
newDiv.style.display = "block";
}
I want to be able to call the function with a number in the bracket like...
onclick="swap2(2)"
And then have the newDiv variable change based on that number like so...
var newDiv = document.getElementById("product-page2");
How can I go about doing this?
function(variable){
// process using 'variable'
}
that's how you pass a variable to a function. Thus:
function swap2(n) {
var oldDiv = document.getElementById("product-grid");
var newDiv = document.getElementById("product-page" + n);
oldDiv.style.display = "none";
newDiv.style.display = "block";
}

Categories

Resources