function for adding new contacts won't work - javascript

I watched a youtube video about coding in vanilla javascript because I'm currently studying javascript. I wanted to add an "adder" for names that start with letter a.
I wrote a do1 function and I added div between all names that start with a. I don't know what's going on here to be host what's the problem. I'm currently moving from basics to intermediate level in javascript, I'm trying to practice my javascript skills in any possible way. function filter names was written by someone else. I don't have that much skills to do something like that.
So if you have any ideas on how should I practice js. If you have any websites or even tasks that could help me in learning javascript. would appreciate if you linked me any in comments section.
let filterInput = document.getElementById('filterInput');
filterInput.addEventListener('keyup', filterNames);
function filterNames() {
// Get value of input
let filterValue = document.getElementById('filterInput').value.toUpperCase();
// Get names ul
let ul = document.getElementById('names');
// Get lis from ul
let li = ul.querySelectorAll('li.collection-item');
// Loop through collection-item lis
for (let i = 0; i < li.length; i++) {
let a = li[i].getElementsByTagName('a')[0];
// If matched
if (a.innerHTML.toUpperCase().indexOf(filterValue) > -1) {
li[i].style.display = '';
} else {
li[i].style.display = 'none';
}
}
}
function do1() {
var input1 = document.getElementById('ipt1').value;
var item = document.createTextNode(input1);
var li = document.createElement('li').className = "collection-header";
var a = document.createElement('a');
var child1 = li.appendChild(a);
var div = document.getElementById('div1');
div1.appendChild(item).innerHTML = item;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.css">
<div class="container">
<h1 class="center-align">
My Contacts
</h1>
<input type="text" id="filterInput" placeholder="Search names...">
<ul id="names" class="collection with-header">
<li class="collection-header">
<h5>A</h5> <input type="box" id="ipt1"> <button onclick="do1();">`click me to add another contact`</button>
</li>
<div id="div1">
<li class="collection-item">
Abe
</li>
<li class="collection-item">
Adam
</li>
<li class="collection-item">
Alan
</li>
<li class="collection-item">
Anna
</li>
</div>
<li class="collection-header">
<h5>B</h5> <input type="box" id="ipt2">
</li>
<li class="collection-item">
Beth
</li>
<li class="collection-item">
Bill
</li>
<li class="collection-item">
Bob
</li>
<li class="collection-item">
Brad
</li>
<li class="collection-header">
<h5>C</h5> <input type="box" id="ipt3">
</li>
<li class="collection-item">
Carrie
</li>
<li class="collection-item">
Cathy
</li>
<li class="collection-item">
Courtney
</li>
</ul>
</div>

Here is a working example:
let filterInput = document.getElementById("filterInput");
filterInput.addEventListener("keyup", filterNames);
function filterNames() {
// Get value of input
let filterValue = document.getElementById("filterInput").value.toUpperCase();
// Get names ul
let ul = document.getElementById("names");
// Get lis from ul
let li = ul.querySelectorAll("li.collection-item");
// Loop through collection-item lis
for (let i = 0; i < li.length; i++) {
let a = li[i].getElementsByTagName("a")[0];
// If matched
if (a.innerHTML.toUpperCase().indexOf(filterValue) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
function do1() {
var input1 = document.getElementById("ipt1").value;
var a = document.createElement("a");
a.textContent = input1;
a.setAttribute('href', "#");
var li = (document.createElement("li"));
li.setAttribute('class', 'collection-item');
li.appendChild(a);
var div = document.getElementById("div1");
div1.appendChild(li);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.css">
<div class="container">
<h1 class="center-align">
My Contacts
</h1>
<input type="text" id="filterInput" placeholder="Search names...">
<ul id="names" class="collection with-header">
<li class="collection-header">
<h5>A</h5> <input type="box" id="ipt1"> <button onclick="do1();">`click me to add another contact`</button>
</li>
<div id="div1">
<li class="collection-item">
Abe
</li>
<li class="collection-item">
Adam
</li>
<li class="collection-item">
Alan
</li>
<li class="collection-item">
Anna
</li>
</div>
<li class="collection-header">
<h5>B</h5> <input type="box" id="ipt2">
</li>
<li class="collection-item">
Beth
</li>
<li class="collection-item">
Bill
</li>
<li class="collection-item">
Bob
</li>
<li class="collection-item">
Brad
</li>
<li class="collection-header">
<h5>C</h5> <input type="box" id="ipt3">
</li>
<li class="collection-item">
Carrie
</li>
<li class="collection-item">
Cathy
</li>
<li class="collection-item">
Courtney
</li>
</ul>
</div>
The issues you were having
var item = document.createTextNode(input1); // this line was not needed as you already had the text
var li = document.createElement('li').className = "collection-header"; // assigning a string here causing errors. Use setAttribute() not class name.
div1.appendChild(item).innerHTML = item; assigning to innerHTML of appended child
so changing the function from:
function do1() {
var input1 = document.getElementById('ipt1').value;
var item = document.createTextNode(input1);
var li = document.createElement('li').className = "collection-header";
var a = document.createElement('a');
var child1 = li.appendChild(a);
var div = document.getElementById('div1');
div1.appendChild(item).innerHTML = item;
}
to :
function do1() {
var input1 = document.getElementById("ipt1").value; // get the value of the input
var a = document.createElement("a"); // create new a tag
a.textContent = input1; // Set the text of the a tag
a.setAttribute('href', "#"); // Set the href attribute of the a tag
var li = (document.createElement("li")); // Create new list item
li.setAttribute('class', 'collection-item'); // Set class attribute of li tag
li.appendChild(a); // Append the a tag to the list item
var div = document.getElementById("div1"); // get the containing div
div1.appendChild(li); // append the new list item to the div
}
Now you are able to append to the first div around A. To append to others, you first would need div tags with different ID's. Then you would just need to either create a new function for each one or pass which div ID you were calling the method on..
Hope this helps.

Look at the following line of code:
var li = document.createElement('li').className = "collection-header";
This code assigns the string "collection-header" to the variable named li. Strings don't have the appendChild function, so your code is crashing on the line:
var child1 = li.appendChild(a);
Not sure what your intention is by using two = in the same line of code. If you can explain that further, perhaps someone can help you achieve your desired result.

Related

How to change the font color of a list in Javascript?

So, I'm trying to make these nav-links of mine to change its color whenever I click a button, but it does not seem to work.
<ul class="nav-links">
<li id = link>Home</li>
<li id = link>Projects</li>
<li id = link>About</li>
<li id = link>Contacts</li>
</ul>
<label class="toggle">
<input type="checkbox" class="check">
<span class="slider" onclick="dark()"></span>
</label>
I tried doing this script but it still doesn't work
const text = document.querySelector(".logo");
const body = document.querySelector("body");
const banner = document.querySelector(".L-banner");
const navLinks = document.getElementById("#link");
function dark(){
text.style.color = "#fff";
body.style.background = "#000";
banner.style.color = "#fff";
for(var i = 0; i < navLinks.length; i++){
navLinks[i].style.color = "#fffff";
}
}
You can't give multiple elements the same ID, and querySelector only selects a single element.
To select all the links, you can use querySelectorAll
document.getElementById('button').addEventListener('click', changeColor);
function changeColor() {
const links = [...document.querySelectorAll('.nav-links li a')];
links.forEach(link => link.style.color = "cornflowerblue");
}
<ul class="nav-links">
<li>
Home
</li>
<li>
Projects
</li>
<li>
About
</li>
<li>
Contacts
</li>
</ul>
<button id="button">Change link color</button>
you should change it to this
const navLinks = document.querySelectorAll("#link a");
also don't forget to fix html
<ul class="nav-links">
<li id="link">Home</li>
<li id="link">Projects</li>
<li id="link" ink>About</li>
<li id="link" ink>Contacts</li>
</ul>

Not able to perform click event on dynamically created html elements

I'm using jquery and creating some ul, li and a dynamically on $('document').ready(). After this the ul-li renders in browser is looks like bellow in html representation
<ul class="ul">
<li class="li">
<a>Some buddy</a>
<ul class="ul">
<li class="li" id="testLi">
<a id="testView">test buddy</a>
</li>
</ul>
</li>
</ul>
Please ignore class names. I have assigned ids to <li> and child` tags. and I also have a function written as bellow:
$(document).ready(function () {
$('#testView').click(function () {
var ul = document.createElement('ul');
ul.className = 'ul';
var li = document.createElement('li');
li.className = 'li';
var a = document.createElement('a');
a.innerHTML = 'test buddy';
$(li).append(a);
$(ul).append(li);
$('#testLi').append(ul);
});
});
Now if I click on <a id="testView">test buddy</a> my function does not get called. I think this because DOM is loaded and my new elements are get created in ready(). Please provide a solution.
You will need to attach the event handler to the document and delegate the event to the element.
You can do something like this:
$(document).on('click', '#testView', function () {
var ul = document.createElement('ul');
ul.className = 'ul';
var li = document.createElement('li');
li.className = 'li';
var a = document.createElement('a');
a.innerHTML = 'test buddy';
$(li).append(a);
$(ul).append(li);
$('#testLi').append(ul);
});
This will apply to all the elements with this id regardless of whether they are created before document.ready() or not.
Your code is working fine. I have added it to the snippet below.
$(document).ready(function() {
$('#testView').click(function() {
var ul = document.createElement('ul');
ul.className = 'ul';
var li = document.createElement('li');
li.className = 'li';
var a = document.createElement('a');
a.innerHTML = 'test buddy';
$(li).append(a);
$(ul).append(li);
$('#testLi').append(ul);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="ul">
<li class="li">
<a>Some buddy</a>
<ul class="ul">
<li class="li" id="testLi">
<a id="testView">test buddy</a>
</li>
</ul>
</li>
</ul>

Add data-attribute to appended object src

I would like to append a link to multiple list-items that passes the data-attribute to the end of the URL. However I don't understand how to make the variable "storyId" hold a different value for each instance of .Story
<div id="InnerPage">
<ol>
<li class="Story" data-id="35213">Text for Link 1 </li>
<li class="Story" data-id="35204">Text for Link 2 </li>
</ol>
</div>
<script>
var storyId = this.getAttribute('data-id');
var sidebarURL = "'index.html?storyid=' + storyId"
var newA = document.createElement('a');
newA.setAttribute('href',sidebarURL);
newA.innerHTML = "Split View";
$('.Story').append([newA]);
</script>
Should result in:
<div id="InnerPage">
<ol>
<li class="Story" data-id="35213">Text for Link 1 Split View</li>
<li class="Story" data-id="35204">Text for Link 2 Split View</li>
</ol>
</div>
http://jsfiddle.net/s3wtsxw5/
You can do:
$("#InnerPage ol li").each(function() {
var id = $(this).data("id");
var link = "index.html?storyid=" + id;
$(this).append("<a href='" + link + "'>Split View</a>");
});

how to dynamically create ul and li elements by for loop in javascript

I am trying to create ul and li element in my codes by using javascript.
my javascript code :
for (var i =0;i<locations.length;i++)
{
//how to dynamic create ul and li code as follow ul and li code?????
}
ul and li code :
<li>
<label for="Device"><SCRIPT LANGUAGE="JavaScript"> document.write("show javascript value like the the locations[i]") </SCRIPT></label> <input type="checkbox" id="Device" />
<ol>
<li class="file">File 1</li>
<li>
<label for="subfolder2">Subfolder 1</label> <input type="checkbox" id="subfolder2" />
<ol>
<li class="file">Subfile 1</li>
<li class="file">Subfile 2</li>
<li class="file">Subfile 3</li>
<li class="file">Subfile 4</li>
<li class="file">Subfile 5</li>
<li class="file">Subfile 6</li>
</ol>
</li>
</ol>
</li>
Check here...
Script:
var ul = document.createElement("ul");
document.body.appendChild(ul);
for (var i = 1; i <= 10; i++)
{
var li = document.createElement("li");
li.className = "file";
var a = document.createElement("a");
a.innerHTML = "Subfile " + i;
li.appendChild(a);
ul.appendChild(li);
}
like this you can create your desired order..
Please check Example
HTML
<li>
<label for="Device"><SCRIPT LANGUAGE="JavaScript"> document.write("show javascript value like the the locations[i]") </SCRIPT></label> <input type="checkbox" id="Device" />
<ol>
<li class="file">File 1</li>
<li>
<label for="subfolder2">Subfolder 1</label> <input type="checkbox" id="subfolder2" />
<div id='mi'></div>
</li>
</ol>
</li>
JS
var text = '<ol>';
for (var i =0;i<6;i++)
{
text = text + "<li class='file'><a href=''>Subfile " + i + "</a></li>";
}
text = text +'</ol>';
document.getElementById('mi').innerHTML=text;
Here i have put <LI> in for loop in js and store it to variable then set it on div html.
I just answered a similar question, earlier, take a look at my example here using some of jQueries effects.
var list = $('#theList li:last-child'),
limit = 20,
current = 0;
function rand() {
return Math.random().toString(36).substr(2); // Just for some random contnt
}
$('#trigger').click(function() { // We're using a static button to start the population of the list
var end = setInterval(function() {
if ( current == limit ) {
current = 0;
clearInterval(end);
}
list.append('<li style="display:none;color:green;">' + rand() + '</li>');
var newList = $('#theList li:last-child');
newList.fadeIn();
var colorEnd = setInterval(function() {
newList.css('color', 'black');
clearInterval(colorEnd);
}, 350);
current = current + 1;
}, 300);
});

Keyboard navigation on nested list using only javascript

I have a ul list as follows. I am new to JS and trying to do a keyboard navigation, just the arrow keys using only javascript.
<ul id= nav>
<li class =subnav id =sub1> Companies
<ul id = hidden>
<li> item 1 </li>
<li> item 2 </li>
<li> item 3 </li>
</ul>
</li>
<li class =subnav id =sub2> LINKS
<ul id = hidden>
<li> item 4 </li>
<li> item 5 </li>
<li> item 6 </li>
</ul>
</li>
</ul>
my JS:
ul = document.getElementById("nav");
li = ul.getElementsByClassName("subnav");
ul2 = document.getElementById("hidden");
li = ul.getElementsByTagName("li");
function keyPress(e)
{
var e = e||window.event;
e =e.which||e.keyCode;
for( var i=0; i<li.length; i++)
{
var f = li[i].childNodes[0];
if(li[i].children.length > 0)
{
for(var j=0; j<li2.length; j++)
{
var x = li2[j].childNodes[0];
}
}
else
{
alert("no child nodes");
}
}
}
I am trying to set focus on the first item and then moving to each nodes using keys.
I suggest using jwerty, awesome keyboard events library.
I used jQuery and jWerty plugin.
Here is a quick JSFiddle: (Click the preview window and start hitting the down key)
http://jsfiddle.net/8QZrV/
As a basic idea, you should create an object with all the elements and then iterate through them, my basic example was like this:
var i = 0;
j = jQuery('.navigator li').length;
And then you hook it up in jwerty, I guess you want to make some actions there, so I guess you should also .focus() the current element.
Enjoy!

Categories