javascripthtmlcss

Creating a simple menu w/ reusable onClick function for different variables


So I have a simple menu for a blog that's working but I'm trying to figure out if there's a way to reuse onClick function. So the menu simply consist of years and months.

2025 Month Month Month entry for month goes here

2024 Month Month Month entry for month goes here

When users clicks on the year, the option to select months for that particular year comes up, then when user clicks on the month a md file will load underneath.

When user clicks on the month the function JAN() executes to load the blog entry.

function JAN() {
    let entry = document.querySelector(`#entry`)
    fetch(`/journal/entries/2025/JAN.md`)
    .then(async r => {
      if (r.ok) {
        mdparse(await r.text(), {"permissive": true, "section": true})
        .then(r => {
          entry.innerHTML = r
        })
      }
    })
  }

What I'm trying to figure out is how to write the JAN() function so it's reusable instead of having write same thing for each month. I was thinking about maybe having a variable inside the function that is dynamic and grabs name from a div id or something like that but not sure how to implement that.

What would be a simple solution for this? Thanks!


Solution

  • You can pass year and month as parameters to make your function dynamic like this:

    function loadEntry(year, month) {
        let entry = document.querySelector('#entry');
        fetch(`/journal/entries/${year}/${month}.md`)
            .then(async r => {
                if (r.ok) {
                    const content = await r.text();
                    const parsedContent = await mdparse(content, {"permissive": true, "section": true});
                    entry.innerHTML = parsedContent;
                }
            });
    }
    

    And call function like this:

    <button onclick="loadEntry(2025, 'JAN')">January 2025</button>
    <button onclick="loadEntry(2024, 'FEB')">February 2025</button>
    

    Let me know if any confusions or need clarity.