javascript function onclick with new elements - javascript

I work on a website, and I have a js problem.
I resume the situation:
I made a dynamic form with some tabs in.
I can switch tabs with a js click function
When I click on the "+" tab , it creates a new tab ( new <li> on the <ul>, and new <div> on main div )
But when I want to go on the new tab freshly created, the click function don't answer.
I put a console.log on the first line of the click function, and no log output.
the click function works well with static content, but with fresh content don't work.
How can I make it works with dynamic content ?
http://jsfiddle.net/npx2mes2/

http://jsfiddle.net/npx2mes2/1/
$("#tabs_menu_n1").on('click', 'a', function(e)
the problem was on registering the event, you should attach it to parent first, and then on every child.

change the line $(".tabs_menu_n1 a").click(function(e) { to $(document).on('click', ".tabs_menu_n1 a", function (e) {
Demo
Explanation.
when the elements are being added to DOM dynamically you must register the for the events every time the element is added. So instead of doing this process every time simply register events like below, therefore you don't want to register the events fro dynamically created elements
$(document).on('click', ".selector", function (e) {));
Now i can add elements with selector class dynamically and can handle click event on the element without registering the click event every time i add the element.
Note: You can use parent selector in place of document

A bit simplified sample without jQuery.
But idea same: add click handler to ul and check inside that clicked a tag.
var x = 2;
var original = document.getElementById('H1_n1');
function a(content, href) {
var link = document.createElement("a");
link.textContent = content;
link.setAttribute('href', href);
return link;
}
function li_a(id, content, href) {
var listItem = document.createElement("li");
listItem.setAttribute('id', id);
listItem.appendChild(a(content, href));
return listItem;
}
function div(id, textContent) {
var d = document.createElement("div");
d.setAttribute('class', 'tab_content_n1')
d.setAttribute('id', id)
d.textContent = textContent;
return d;
}
function add_rec() {
var i = x++;
var mdiv = document.getElementById("tab_n1");
mdiv.appendChild(div('H1_n' + i, '\nHello world from n' + i + '.\n'));
pbtn = document.getElementById('pbtn');
var ul = document.getElementById("tabs_menu_n1");
ul.insertBefore(li_a("hn" + i, "H" + i, "#H1_n" + i), pbtn);
}
document.getElementById('tabs_menu_n1').addEventListener('click', function(e) {
var el = e.target;
if (el.nodeName !== 'A') return;
if (el.hash == "#+") add_rec();
else {
e.preventDefault();
var current = document.querySelectorAll("#tabs_menu_n1 .current, #tab_n1 .current");
for (var i = 0, len = current.length; i < len; i++) {
current[i].classList.remove('current');
}
el.classList.add('current');
document.querySelector(el.hash).classList.add('current');
}
}, false);
.tab_content_n1 {
display: none;
}
.tab_content_n1.current {
display: block;
animation: fadeIn 1s;
}
a.current {
color: red;
}
#keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
<div class="tab_space">
<ul id="tabs_menu_n1" class="nav nav-tabs tabs_menu_n1 tab_body">
<li><a class="current" href="#M_n1">mai</a>
</li>
<li>red
</li>
<li id="hn1">hor
</li>
<li id="pbtn">+
</li>
</ul>
</div>
<div id="tab_n1" class="tab_n1">
<div class="tab_content_n1 current" id="M_n1">mai</div>
<div class="tab_content_n1" id="R_n1">red</div>
<div class="tab_content_n1" id="H1_n1">hor</div>
</div>

Related

Anchor Tag href functions

I am trying to create a function that finds the id of an element that an anchor tag directs to, and attach a class to that element. I need this to be vanilla js not jquery.
For Example:
<div id="firstDiv"></div>
<div> Destination </div>
<div> Destination #2 </div>
The idea would be that once you click on the anchor tag that it would take you to the div and attach a class to that div to initiate a function.
The script that I've written runs for loops that add the values of the href attribute and the id attribute from javascript objects. See Below:
var rooms = [
{
id: 1,
name: Example,
},
{
id:2,
name: Example #2,
}
]
for ( x in rooms ) {
var i = document.getElementById("firstDiv");
var a = document.createElement("a");
i.appendChild(a);
a.href = "#" + rooms[x].id;
a.innerHTML += rooms[x].name + "<br>";
a.classList.add("show");
}
var rect = document.getElementsByTagName("rect");
for ( i = 0; i < rect.length; i++ ) {
rect[i].setAttribute("id", rooms[i].id);
}
Output:
<div id="firstDiv">
Example
Example #2
</div>
<div id="1"> Destination </div>
<div id="2"> Destination #2 </div>
The function below is an example of what I want the function to do for each corresponding div when an a tag is clicked.
function attach() {
var div = document.getElementById(rooms[i].id);
div.classList.toggle("active");
}
Any advice on how to properly write this function for my particular needs. Would a for loop be best for this or an if/else statement. I've tried both but neither has worked.
Please let me know if I need to clarify more.
It seems like this is what you are asking about. See comments inline.
document.addEventListener("click", function(event){
// First, check to see if it was an anchor that was clicked
// in the document
if(event.target.nodeName === "A"){
// If so, add a class to the target
// Get the href attribute and strip off the "#", then find that element and toggle the class
document.getElementById(event.target.getAttribute("href").replace("#","")).classList.toggle("highlight");
}
});
.highlight { background-color:yellow; }
<div id="firstDiv">
Example
Example #2
</div>
<div id="one"> Destination </div>
<div id="two"> Destination #2 </div>
Try this:
let anchors = document.querySelectorAll("#firstDiv a");
for (let i = 0; i < anchors.length; i++) {
anchors[i].addEventListener("click", () => {
var div = document.getElementById(rooms[i].id);
div.classList.toggle("active");
}
You're almost there you just need to add an onclick property for the anchor tag now you can or cannot use the third attach function.I am including both implementations for your reference.
for ( x in rooms ) {
var i = document.getElementById("firstDiv");
var a = document.createElement("a");
i.appendChild(a);
a.href = "#" + rooms[x].id;
a.innerHTML += rooms[x].name + "<br>";
a.classList.add("show");
a.onClick=`document.getElementById(${rooms[x].id}).classList.toggle("active")`;
}
If you want to have a dedicated function your loop becomes
for ( x in rooms ) {
var i = document.getElementById("firstDiv");
var a = document.createElement("a");
i.appendChild(a);
a.href = "#" + rooms[x].id;
a.innerHTML += rooms[x].name + "<br>";
a.classList.add("show");
a.onClick=`attach(${rooms[x].id})`;
}
Your attach function then becomes:
function attach(id) {
var div = document.getElementById(id);
div.classList.toggle("active");
}
Do let me know if you have any issues.
CSS Only 😎
This is a bit off-topic but you can use the :target selector to set the style of the corresponding id without JS.
/* element with an id matching the URL fragment */
:target {
background: gold;
}
/* you can combine target with other selectors */
#c:target {
background: orange
}
/* just a bit of styling */
a,div {
padding: .5rem;
display: block;
width: 20%;
float:left;
}
Link to A
Link to B
Link to C
Link to D
<div id="a">A</div>
<div id="b">B</div>
<div id="c">C</div>
<div id="d">D</div>

How do I attach placeholder to the button through JS' DOM?

I am trying to figure out how to attach button 'Delete' to the each list element making so in advance that I will be able to make more buttons for additional list elements later.But when I create buttons,they appear without the text,just tiny rectangle box near the text.I wanted to fix through command 'document.getElementByClassName[list_number + "_button"].placeholder = "Delete",but I got an error even earlier trying to attach classnames to the buttons:
Uncaught TypeError: Cannot read property 'classList' of undefined
at addButton (script.js:74)
at script.js:82
But what's strange is that this error shows only at the [1] list object,not the the [0].For some reason with [0] object everything goes OK,although I didn't succeed in attaching name to it.I thought that the problem laid in list numeration,because the first button is actually "Send',but when I changed the value of var list_number = 0 from 0 to 1,it only got worse and gave an error right away.
How do I attach text in the buttons so they will look normal?
Note:the commands related to the buttons are at the end,everything earlier are command to add new elements to the list trhough input and make the elements line-through
CODE
var button = document.getElementById("button");
var modify_list = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.querySelectorAll("li");
var all_buttons = document.querySelectorAll("button");
var i = 0; //Attach classes to the li
while (li.length > i) {
li[i].classList.add(i);
li[i].classList.add('done');
li[i].classList.add('cursor');
i++
}
//Toggle the line-through function(later we will cal the function that will toggle once more when clicked on element of the list.
var n = 0
while (li.length > n) {
li[n].classList.toggle("done");
n++
}
//Command to add new elements to the list and make line-thorugh when clicked.
function inputLength() {
return modify_list.value.length;
}
function addToTheList() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(modify_list.value));
ul.appendChild(li);
modify_list.value = '';
}
function addAfterClick() {
if (inputLength() === 0) {
alert("Please,don\'t enter the empty list");
} else {
addToTheList();
}
}
function addAfterEnter(key) {
if (key.keyCode === 13 && inputLength() > 0) {
addToTheList();
}
}
button.addEventListener("click", addAfterClick);
modify_list.addEventListener("keypress", addAfterEnter);
function toggle(number) {
li[number].classList.toggle("done");
}
ul.addEventListener("click", whenClicked);
function whenClicked(event) {
var li_number = event.target.className[0];
//In JS it doesn't matter in some occasions if it's a string or number,I suppouse.
// var li_number = Number(li_number_string);
// console.log(li_number);
toggle(li_number);
}
// Create buttons and their functions
function addButton(list_number) {
var button = document.createElement("button");
li[list_number].appendChild(button); //append button near the respective li objects
all_buttons[list_number].classList.add(list_number + "_button") //create class for the button
console.log(all_buttons[list_number].classList);
// document.getElementByClassName[list_number + "_button"].placeholder = "Delete"
}
var list_number = 0 // because under number 0 we have "Send" button
while (li.length > list_number) {
addButton(list_number);
list_number++;
}
// console.log(list_number);
.done {
color: red;
text-decoration: line-through;
}
.cursor {
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title>DOM</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>What plans do I have till the end of the summer?</h1>
<p>They are:</p>
<input type="text" name="add activities" id="userinput" placeholder="add activities">
<button id="button">Send</button>
<ul>
<li>Learn German</li>
<li>Learn Japanese</li>
<li>Learn Java Script</li>
<li>Physical activities</li>
</ul>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
The text you want to be displayed on a programatically generated HTMLButtonElement can be set using it's .innerText property. The .placeholder property serves a different purpose.
Let's take a closer look at your addButton function:
function addButton(list_number){
var button = document.createElement("button");
li[list_number].appendChild(button); //append button near the respective li objects
all_buttons[list_number].classList.add(list_number + "_button") //create class for the button
console.log(all_buttons[list_number].classList);
// document.getElementByClassName[list_number + "_button"].placeholder = "Delete"
}
The first two lines are okay. Trouble starts here:
all_buttons[list_number].classList.add(list_number + "_button");
all_buttons is a HTML collection of buttons you initialized before you started adding dynamically generated button elements to the DOM thus it just contains the buttons set up via HTML. That means this array is outdated and would need to be updated every time you add or remove buttons.
Furthermore you don't need to use that array at all if you want to manipulate properties of your freshly generated button - you can directly access it using the variable button. I'd also recommend giving those buttons an unique id, so you can reference them later on and give it a click event listener for example. Also since there is already a global variable named button you should give the variable inside the function a different name e.g. localButton.
Here's an example:
var button = document.getElementById("button");
var modify_list = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.querySelectorAll("li");
var all_buttons = document.querySelectorAll("button");
var i = 0; //Attach classes to the li
while (li.length > i) {
li[i].classList.add(i);
li[i].classList.add('done');
li[i].classList.add('cursor');
i++
}
//Toggle the line-through function(later we will cal the function that will toggle once more when clicked on element of the list.
var n = 0;
while (li.length > n) {
li[n].classList.toggle("done");
n++;
}
//Command to add new elements to the list and make line-thorugh when clicked.
function inputLength() {
return modify_list.value.length;
}
function addToTheList() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(modify_list.value));
ul.appendChild(li);
modify_list.value = '';
}
function addAfterClick() {
if (inputLength() === 0) {
alert("Please,don\'t enter the empty list");
} else {
addToTheList();
}
}
function addAfterEnter(key) {
if (key.keyCode === 13 && inputLength() > 0) {
addToTheList();
}
}
button.addEventListener("click", addAfterClick);
modify_list.addEventListener("keypress", addAfterEnter);
function toggle(number) {
li[number].classList.toggle("done");
}
ul.addEventListener("click", whenClicked);
function whenClicked(event) {
var li_number = event.target.className[0];
//In JS it doesn't matter in some occasions if it's a string or number,I suppouse.
// var li_number = Number(li_number_string);
// console.log(li_number);
toggle(li_number);
}
// Create buttons and their functions
function addButton(list_number) {
var localButton = document.createElement("button");
localButton.innerText = "Delete";
localButton.id = "myButton" + list_number;
li[list_number].appendChild(localButton);
}
var list_number = 0 // because under number 0 we have "Send" button
while (li.length > list_number) {
addButton(list_number);
list_number++;
}
.done {
color: red;
text-decoration: line-through;
}
.cursor {
cursor: pointer;
}
<h1>What plans do I have till the end of the summer?</h1>
<p>They are:</p>
<input type="text" name="add activities" id="userinput" placeholder="add activities">
<button id="button">Send</button>
<ul>
<li>Learn German</li>
<li>Learn Japanese</li>
<li>Learn Java Script</li>
<li>Physical activities</li>
</ul>

How to select a new added element and edit it?

I have an <a> element:
<a id='addNewElementk' onclick='//Some Js Code' class='continueButton'>Click To Add</a>
When this anchor is clicked , A new element added:
New Added Element
And the first anchor which was clicked , Is removed.
I want to select that new element.
I tried:
window.onload = function(){
var newElem = document.getElementsByClassName('continueButton')[1];
alert(newElem.innerHTML);
}
I'm using ('continueButton')[1] , As there is another input with the same class before that anchor.
But for sure I get Click To Add from the first one , As that's was found when the page is loaded.
So how can I select that new element?
You're attempting to select the element before it exists in the DOM.
You instead need to run that code within the click event handler of the first <a>, like this:
window.onload = function() {
document.querySelector('#addNewElementk').addEventListener('click', function(e) {
e.preventDefault();
var a = document.createElement('a');
a.textContent = 'New Added Element';
a.href = '#';
a.classList.add('continueButton');
a.addEventListener('click', function(e) {
console.log(a.innerHTML);
});
this.parentNode.insertBefore(a, this);
this.remove();
});
}
<a id='addNewElementk' href="#" class='continueButton'>Click To Add</a>
Note the use of addEventListener() over the outdated on* event attributes which should be avoided.
You are attempting to select on an element that doesn't exist in the DOM. Dynamically added elements can be accessed in a couple of ways, above someone has an answer that adds an event listener to the created element which is a solid solution. The other most common way would be to use event delegation (if you are familiar with jQuery that would be $(parentElement).on('action', 'elementWeWantToWatch', function)) in Vanilla js the pattern is effectively the same, find or make a container element for your dynamic html, then add a listener to that container. Inside the listener you will want to ensure the target matches whatever your dynamic selection would be and execute when you find a match.
In this Example
The event listener is initiated on page load to watch the container element. The listener watches for clicks on elements with the continueButton class and when it finds one it removes the clicked element and adds a new element (the counter is to demonstrate that new content is being displayed :D)
(function() {
let i = 1;
const makeButton = () => {
const a = document.createElement('a');
a.classList.add('continueButton');
a.href = '#';
a.textContent = `Button ${i}`
i++;
return a;
}
const init = () => {
const container = document.querySelector('.test');
container.addEventListener('click', e => {
if (e.target.classList.contains('continueButton')) {
let button = makeButton();
container.appendChild(button);
container.removeChild(e.target);
return;
}
});
};
if (document.readyState == 'loading') {
window.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})()
.test {
width: 100%;
display: block;
text-align: center;
}
.continueButton {
display: block;
color: white;
background-color: green;
border-radius 2px;
padding: 15px 30px;
line-height: 2;
margin: 50px auto;
width: 200px;
text-decoration: none
}
<section class="test">
<a id='addNewElementk' class='continueButton'>Click To Add</a>
</section>

Eventlisteners not being added in the following js code

I am building a todo app where I am dynamically generating tasks using javascript.[]
I generate following equivalent html from js whenever I click on the add button:
<div class="row datasection">
<div class="todo">
<div class="databox col s6 offset-s1 waves-effect">
<p class="checkglyph1 checkglyph2">Task no 1</p>
<a>
<i class="material-icons checkglyph checkglyph1 checkglyph2 glyphcolor">check</i>
</a>
</div>
</div>
</div>
Now what I want is whenever I click event on the task created it should become yellow in colour.I have written the code to this. below.However it works fine only when there is one task created.If there is multiple then the last task works well but actionlistener on the first one does not seem to be working.I am not able to figure out where the code is breaking.
var glyph= document.querySelectorAll(".glyphcolor");
for (var i = 0; i < glyph.length; i++) {
glyph[i].addEventListener('click', function(event) {
this.classList.toggle("checkglyph1");
});
}
The actual snippet
//declaration
var calendardata = document.getElementById('date1');
var addbutton = document.querySelector('.addbutton');
var todo = document.querySelector('.todo');
addbutton.addEventListener('click', function() {
/* body to return the html */
if (data.value) {
var newdiv = document.createElement("div"); // Create a <button> element
newdiv.classList.add("databox", "col", "s6", "waves-effect");
//console.log(newdiv);
todo.appendChild(newdiv);
//console.log(newdiv.parentNode);
var newpar = document.createElement("p");
newpar.classList.add("checkglyph1", "checkglyph2");
var node = document.createTextNode(data.value + "." + " " +
calendardata.value);
var newa = document.createElement("a");
newdiv.appendChild(newa)
var newglyph = document.createElement("i");
newglyph.classList.add("material-icons", "checkglyph", "checkglyph1",
"checkglyph2", "glyphcolor");
var node1 = document.createTextNode("check");
newa.appendChild(newglyph);
newglyph.append(node1);
newpar.appendChild(node);
newdiv.appendChild(newpar);
data.value = "";
calendardata.value = "";
created = true;
// console.log("before glyh created");
//code to perform action on the click of the tick symbol
var glyph = document.querySelectorAll(".glyphcolor");
var par = document.getElementsByClassName('checkglyph2');
for (var i = 0; i < glyph.length; i++) {
//console.log("Inside the loop");
glyph[i].addEventListener('click', function.bind(event) {
this.classList.toggle("checkglyph1");
//console.log('Inside the click');
//console.log(i);
});
}
}
})
What's happening that when they other tasks are created they aren't being collected in the Node Collection, thus they have no event listener. What you can do is instead add the event listener to the container and change whichever item that was clicked in:
document.querySelector('ul').addEventListener('click', changeClass);
document.querySelector('#button').addEventListener('click', addLi);
function changeClass(e){
e.target.closest('li').classList.toggle('checkglyph1');
}
function addLi(e){
const new_li = document.createElement('li');
new_li.textContent = document.querySelectorAll('li').length + 1;
new_li.classList.add('checkglyph1');
document.querySelector('ul').appendChild(new_li);
}
li:not(.checkglyph1) {
background: #f00;
}
<button id="button">Add li</button>
<ul>
<li class="checkglyph1">1</li>
<li class="checkglyph1">2</li>
<li class="checkglyph1 red">3</li>
<li class="checkglyph1">4</li>
<li class="checkglyph1">5</li>
<li class="checkglyph1">6</li>
<li class="checkglyph1">7</li>
<li class="checkglyph1">8</li>
<li class="checkglyph1">9</li>
<li class="checkglyph1">10</li>
</ul>
The problem with your code is that everytime you click on ".addbutton", you're going through all of the ".glyphcolor"s element's in your DOM and adding a new onclick event listener. The last one created will work, but the others will have multiple event listeners repeated (yes, this is possible). So, when you click on an element that has two events telling it to toggle the "checkglyph1" class, it will do it twice. And of course, it will not change at all. You can easily see this happening, because all the odd elements in your page must work (they will toggle the class by odd times), while the even ones must not.
This can be corrected by adding the event listener directly on the element when you create it on the page. The code below must work fine:
//declaration
var calendardata = document.getElementById('date1');
var addbutton = document.querySelector('.addbutton');
var todo = document.querySelector('.todo');
addbutton.addEventListener('click', function() {
if (data.value) {
var newdiv = document.createElement("div"); // Create a <button> element
newdiv.classList.add("databox", "col", "s6", "waves-effect");
//console.log(newdiv);
todo.appendChild(newdiv);
//console.log(newdiv.parentNode);
var newpar = document.createElement("p");
newpar.classList.add("checkglyph1", "checkglyph2");
var node = document.createTextNode(data.value + "." + " " +
calendardata.value);
var newa = document.createElement("a");
newdiv.appendChild(newa)
var newglyph = document.createElement("i");
newglyph.classList.add("material-icons", "checkglyph", "checkglyph1",
"checkglyph2", "glyphcolor");
var node1 = document.createTextNode("check");
newa.appendChild(newglyph);
newglyph.append(node1);
newpar.appendChild(node);
newdiv.appendChild(newpar);
data.value = "";
calendardata.value = "";
created = true;
newglyph.addEventListener('click', function(event) {
event.preventDefault(); // Just to prevent non desired effects of click
newglyph.classList.toggle('checkglyph1');
}
}
}
And just small clarifications: you don't need the "bind" in your actual code.
glyph[i].addEventListener('click', function.bind(event) { // just type function(event)
this.classList.toggle('checkglyph1');...

include variable with addEventListener

I´ve just started to learn JavaScript and made a click function to change value of i depending on which li element is being clicked. Instead of having 3x of basically same function is it possible to send variable with addEventLisener to check with a if statement. Because if I add 1 or 2 more li it would add a lot of unnecessary code.
HTML:
<div><img src="image1" />
<ul>
<li id="list1">1</li>
<li id="list2">2</li>
<li id="list3">3</li>
</ul>
</div>
JavaScript:
var list1 = getElementById('list1');
var list2 = getElementById('list2');
var list3 = getElementById('list3');
list1.addEventListener("click", clicked1);
list2.addEventListener("click", clicked2);
list3.addEventListener("click", clicked3);
var i = 0;
function clicked1(){
i= 0;
loop();
}
function clicked2(){
i = 1;
loop();
}
function clicked3(){
i = 2;
loop();
}
function loop(){
if (i > 2){
i=0;
}
var imageloop = getElementById('slideshow').getElementsByTagName('img');
imageloop[0].src = 'image' + i;
i++
setTimeout(loop,3000);
}
So when one of the li element is being clicked it will change the img currently displaying.
Bind to the list, not the list item - <ul id="ul1">... :
document.getElementById('ul1').addEventListener('click', function (e) {
var li = e.target;
alert(li.id); // list1, list2, respectively, etc.
});
http://jsfiddle.net/seancannon/D6HX4/
As Teemu said, bind to the list and use e.target. Then, change i according to e.target.innerHTML (because for your purposes, that's easier since the innerHTML is similar to the id, but simpler).
Assuming the <ul> element now has an id of "list":
var list = document.getElementById("list");
var i = null;
list.addEventListener("click", function(e) {
window.i = parseInt(e.target.innerHTML, 10);
console.log(window.i);
});
You don't need Separate code for each <li>,
Here is How to do it in single function:
HTML:
<div>
<ul id="All_List">
<li id="list1">1</li>
<li id="list2">2</li>
<li id="list3">3</li>
</ul>
</div>
JavaScript:
var clicked_li=0; /* It'll store the number of <li> being clicked */
var ul=document.getElementById("All_List"); /* <ul> Element with all <li> */
window.onload=function(){
var lis=ul.getElementsByTagName("li"); /* All <li>'s from <ul> */
for(var i=0;i<lis.length;i++){
var li=lis[i]; /* Specific <li> from <ul> ie, lis[0] means first <li> of <ul> */
li.addEventListener("click", function(){ /* Listen and bind click event to that <li> */
clicked_li=getIndex(this); /* Store Which <li> Was clicked in clicked_li */
alert("'list"+clicked_li+"' was clicked!");
/* if you just want to get the id you can use event.target.id; instead of getIndex(); */
}, false);
}
};
function getIndex(node) {
var childs = node.parentNode.getElementsByTagName("li"); /* Get parent <ul> and all child <li> of that parent */
for (var i = 0; i < childs.length; i++) {
if (node == childs[i]) break; /* Find which <li> from current <ul> was clicked */
}
return (i+1); /* Return No.(index) of that <li> starting with 1 */
}
and here is the:
fiddle for the same.
Hope it'll help you. Cheers!
This is an "improve/clearer" of Vedant Terkar answer. Which may give a more clear aspect on
the answer he gave.
if we give ul id group. We dont need id for each of the list-item inside the ul.
<ul id="group">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Javascript
var i=0;
we set i to be a global variable and equal to 0 assuming it will display image(0) if nothing else is called.
window.onload=function(){
var lis=document.getElementById("group").getElementsByTagName('li');
We are now creating a Nodelist which is called lis. Then we loop through the NodeList to se which list-element is being clicked at.
for(i=0;i<lis.length;i++){
var li=lis[i];
li.addEventListener("click",index, false);
}
}
function index(){
var lis = document.getElementById("group").getElementsByTagName('li');
i = getIndex(this);
for(var a=0; a < lis.length; a++){
if(a ==i){
lis[i].innerHTML = 'Choosen';
}else{
lis[a].innerHTML = 'list'+a;
}
}
}
function getIndex(node) {
var childs = node.parentNode.getElementsByTagName("li");
for (var i = 0; i < childs.length; i++) {
if (node == childs[i]) break;
}
return (i);
}

Categories

Resources