Home > Mobile >  Create dynamic menu with javascript
Create dynamic menu with javascript

Time:07-20

I try to create a menu with my rather weak javascript skills.

My html page looks like :

<html>
  <head>
    ...
  </head>
  <body>
    <article >
      <h2>Title 1</h2>
      <h2>Title 2</h2>
      <h2>Title 3</h2>
    </article>
  </body>
</html>

My script :

var allH2 = Array.from(document.querySelectorAll("h2"));
var article = document.querySelector("article");

document.body.onload = addMenu;

function addMenu () {
    var menu = document.createElement("div");
    menu.setAttribute("class", "menu");

    var menu_title = document.createElement("h2");
    var title = document.createTextNode("Menu");
    menu_title.appendChild(title);

    menu.appendChild(menu_title);

    var list = document.createElement("ul");
    list.setAttribute("class", "list");

    menu.appendChild(list);

    allH2.forEach(function callback(element, index) {
        var link = document.createElement("a");
        var content = document.createTextNode(element.textContent);
        var list_element = document.createElement("li");
        var href_el = document.querySelectorAll("h2")[index].href;
        list_element.setAttribute("class", "list-element");
        link.setAttribute("href", href_el);
        link.appendChild(content);
        list_element.appendChild(link);
        list.appendChild(list_element);
    });

    document.body.insertBefore(menu, article);
}

The problem is that the .href in the forEach returns me undefined and then the links don't work.

PS: Sorry, my English level is rather low :'c

CodePudding user response:

This line is going to try to fetch the link from the h2 tag which it doesn't have:

var href_el = document.querySelectorAll("h2")[index].href;

if you want to be able to click a link and scroll to that part of the page you can either use js or url fragments. I would suggest url fragments for simplicity.

A url fragment link will scroll to the item with the corresponding id (an element with href="#thediv" would scroll to the element with id="thediv")

you could try this:

var href_el = '#htwo'   index;
document.querySelectorAll("h2").id = 'htwo'   index;

CodePudding user response:

This is happening because you are trying to get the href attribute from the h2 elements, but they don't have it (at least in the HTML snippet you posted).

I created a quick StackBlitz to show the problem here.

To solve this problem, you could add an href attribute to the h2 elements, but i suggest you to prefix it with data-href because it is a custom attribute. More on that here

  • Related