Javascript - Navigation As A Loop
Solution 1:
OK, it's really difficult to understand exactly what you ask for, but here (a bit hacky) an example. I hope that it can help you in the right direction.
var items = document.getElementById('items');
var main = document.getElementById('main');
items.addEventListener('click', e => {
e.preventDefault();
if (e.target.nodeName == 'A') {
console.log(`You clicked ${e.target.attributes['href'].value}`);
}
});
document.forms.new.addEventListener('submit', e => {
e.preventDefault();
let newid = items.children.length + 1;
console.log(newid);
let li = `<li><a href="#div${newid}">Div${newid}-name</a></li>`;
items.innerHTML += li;
let div = `<div class="divdiv" id="div${newid}">
<h3>DIV TITLE</h3><br>Description<br><p>Description</p><hr></div>`;
main.innerHTML += div;
});
<ulid="items"><li><ahref="#div1">Div1-name</a></li><li><ahref="#div2">Div2-name</a></li><li><ahref="#div3">Div3-name</a></li></ul><formname="new"><button>Add new</button></form><divid="main"></div>
Solution 2:
Keep the navigation details in an array, and then iterate over it.
Use
DOMParser
to parse the HTML the user adds to extract the navigation information.
const arr = [
{ href: "div1", name: 'Div1-name' },
{ href: "div2", name: 'Div2-name' },
{ href: "div3", name: 'Div3-name' }
];
const nav = document.querySelector('#nav');
const main = document.querySelector('#main');
const text = document.querySelector('textarea');
const button = document.querySelector('button');
button.addEventListener('click', handleInput, false);
const parser = newDOMParser();
functionhandleInput() {
// Add the HTML to the page
main.insertAdjacentHTML('beforeend', text.value);
// Parse the HTMLconst frag = parser.parseFromString(text.value, 'text/html');
// Extract the id (href) and nameconst href = frag.querySelector('div').id;
const name = frag.querySelector('h3').textContent;
// Add this to the navigation array// to the array
arr.push({ href: `#${href}`, name: name });
updateView();
}
functionupdateView() {
// `map` is useful here. It will produce a new array// (of HTML), but make sure you `join` it up at the endconst links = arr.map(({ href, name }) => {
return`<li><a href="${href}">${name}</a></li>`;
}).join('');
nav.innerHTML = `<ul>${links}</ul>`;
}
updateView();
<divid="nav"></div>
Add HTML:
<textarea></textarea><button>Add</button><divid="main"></div>
Post a Comment for "Javascript - Navigation As A Loop"