# Badge in Navbar

**URL:** <https://forum.bootstrapstudio.io/t/badge-in-navbar/11719>\
**Category:** Webdesign Help\
**Created:** [October 8, 2024, 4:45pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719 "2024-10-08T16:45:53Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![parmaster](https://forum.bootstrapstudio.io/letter_avatar_proxy/v4/letter/p/df788c/32.png) [@parmaster](https://forum.bootstrapstudio.io/u/parmaster)\
**Post date:** [October 8, 2024, 4:45pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/1 "2024-10-08T16:45:53Z")

</div>

Hello!

I don’t know if I’m in the right category but I have an idea and want to ask either this is possible or if someone had done this already.

For example I have a “blog” site where every now and then I will post a “new” article.  
In the navbar is a button linked to the site.

Is it possible to add a badge (or something similar) to the button with a number of “unread” articles since last visit?

It is just an idea but would be nice (at least for me) if this is possible.

Thank you!

Kind regards

Alex

---

<div class="post-metadata">

**Author:** ![xneo](https://forum.bootstrapstudio.io/user_avatar/forum.bootstrapstudio.io/xneo/32/5059_2.png) [@xneo](https://forum.bootstrapstudio.io/u/xneo)\
**Post date:** [October 8, 2024, 5:26pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/2 "2024-10-08T17:26:46Z")

</div>

yes but you have to use mysql. I

---

<div class="post-metadata">

**Author:** ![richards](https://forum.bootstrapstudio.io/user_avatar/forum.bootstrapstudio.io/richards/32/3163_2.png) [@richards](https://forum.bootstrapstudio.io/u/richards)\
**Post date:** [October 8, 2024, 5:43pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/3 "2024-10-08T17:43:44Z")

</div>

HTML you can used the badge component and drag it into your navbar button.

You can find more on positioning here:

> **[Badges](https://getbootstrap.com/docs/5.3/components/badge/#positioned)**
>
> Documentation and examples for badges, our small count and labeling component.

With regards to showing the actual number, if you are using a CMS there may be something in the system that is useable.

Post as much information on here how you are creating your articles and someone might be able to help.

---

<div class="post-metadata">

**Author:** ![parmaster](https://forum.bootstrapstudio.io/letter_avatar_proxy/v4/letter/p/df788c/32.png) [@parmaster](https://forum.bootstrapstudio.io/u/parmaster)\
**Post date:** [October 8, 2024, 6:04pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/4 "2024-10-08T18:04:24Z")

</div>

Thanks for your reply.

There is no backend or cms or something else, it’s just a normal html site from BSS and the articles are built with divs, columns, etc.

---

<div class="post-metadata">

**Author:** ![richards](https://forum.bootstrapstudio.io/user_avatar/forum.bootstrapstudio.io/richards/32/3163_2.png) [@richards](https://forum.bootstrapstudio.io/u/richards)\
**Post date:** [October 8, 2024, 7:58pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/5 "2024-10-08T19:58:42Z")

</div>

You could try using javascript to store the last time the user was on the site and store it in localstorage, then check to see what articles have been published after the last visit.

When you create a new article you would need to update the publishDate in the articles array

```auto
const articles = [
  { publishDate: 1728416433744 },
  { publishDate: 1728416615919 },
  { publishDate: 1728415954441 },

  // ... more articles ...
];

// Function to store the current time in localStorage
function storeLastViewTime() {
  try {
    localStorage.setItem("lastViewTime", Date.now());

// uncomment the line below
 // localStorage.setItem('lastViewTime', 1728416342692);

  } catch (error) {
    console.error("Error storing last view time:", error);
  }
}

// Function to get the stored last view time
function getLastViewTime() {
  try {
    return parseInt(localStorage.getItem("lastViewTime") || 0);
  } catch (error) {
    console.error("Error retrieving last view time:", error);
    return 0;
  }
}

// Function to calculate the number of new articles
function countNewArticles(articles, lastViewTime) {
  const currentTime = Date.now();
  return articles.filter(
    (article) =>
      article.publishDate > lastViewTime && article.publishDate <= currentTime
  ).length;
}

// Function to display the badge
function displayBadge(count) {
  //set articlesContainer to be navigation link with class of articles
  const articlesContainer = document.querySelector(".articles");

  //create the badge
  const badgeElement = document.createElement("span");
  badgeElement.textContent = `${count}`;
  badgeElement.classList.add(
    "badge",
    "bg-primary",
    "position-right",
    "position-absolute",
    "top-0",
    "start-100",
    "translate-middle"
  );

  //show the badge
  articlesContainer.appendChild(badgeElement);
}

// Main function to handle everything
function handleNewArticlesBadge() {
  // Store the current time

  // Get the stored last view time
  const lastViewTime = getLastViewTime();
  storeLastViewTime();

  // Assume we have access to all articles here
  // In a real scenario, you'd likely fetch this data from an API
  

  // Calculate the number of new articles
  const newArticleCount = countNewArticles(articles, lastViewTime);

  // Display the badge if not zero
  if (newArticleCount !=0) {
  displayBadge(newArticleCount);
}

}

// Call the main function when the page loads
document.addEventListener("DOMContentLoaded", handleNewArticlesBadge);

```

In your navbar give the link that you want the badge to display a class of articles.

---

<div class="post-metadata">

**Author:** ![richards](https://forum.bootstrapstudio.io/user_avatar/forum.bootstrapstudio.io/richards/32/3163_2.png) [@richards](https://forum.bootstrapstudio.io/u/richards)\
**Post date:** [October 8, 2024, 8:01pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/6 "2024-10-08T20:01:54Z")

</div>

If you need something to create your publish date timestamps:

https://codepen.io/RichardS1/embed/preview/NWQROBq?default-tabs=js%2Cresult&height=300&host=https%3A%2F%2Fcodepen.io&slug-hash=NWQROBq

---

<div class="post-metadata">

**Author:** ![parmaster](https://forum.bootstrapstudio.io/letter_avatar_proxy/v4/letter/p/df788c/32.png) [@parmaster](https://forum.bootstrapstudio.io/u/parmaster)\
**Post date:** [October 9, 2024, 4:04pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/7 "2024-10-09T16:04:02Z")

</div>

Wow, that’s really impressive.  
I guess I really need to learn JS.

I have only one question:  
Where can you specify which html page should be looked for in the JS file or where do you have to mark the article in the html page so that it is recognized by the JS file?

---

<div class="post-metadata">

**Author:** ![richards](https://forum.bootstrapstudio.io/user_avatar/forum.bootstrapstudio.io/richards/32/3163_2.png) [@richards](https://forum.bootstrapstudio.io/u/richards)\
**Post date:** [October 9, 2024, 5:23pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/8 "2024-10-09T17:23:08Z")

</div>

> [@parmaster](#):
>
> Where can you specify which html page should be looked for in the JS file or where do you have to mark the article in the html page so that it is recognized by the JS file?

You don’t need to. When you create a new article, you will need to add the publish date to the array:

```auto
const articles = [
  { publishDate: 1728416433744 },
  { publishDate: 1728416615919 },
  { publishDate: 1728415954441 },

  // ... more articles ...
];

```

---

<div class="post-metadata">

**Author:** ![parmaster](https://forum.bootstrapstudio.io/letter_avatar_proxy/v4/letter/p/df788c/32.png) [@parmaster](https://forum.bootstrapstudio.io/u/parmaster)\
**Post date:** [October 9, 2024, 6:12pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/9 "2024-10-09T18:12:27Z")

</div>

Ah ok, now I understand!

Thank you so much!

I don’t know if this is possible but you should release it as a component. 👍

---

<div class="post-metadata">

**Author:** ![parmaster](https://forum.bootstrapstudio.io/letter_avatar_proxy/v4/letter/p/df788c/32.png) [@parmaster](https://forum.bootstrapstudio.io/u/parmaster)\
**Post date:** [October 11, 2024, 3:37pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/10 "2024-10-11T15:37:11Z")

</div>

> [@richards](#):
>
> ```auto
> // uncomment the line below
> // localStorage.setItem('lastViewTime', 1728416342692);
> 
> ```

Do I need to uncomment this line and change the timespan every time or do I only need to add a new line at the const articles?

I tried it both ways but I never see the badge.

---

<div class="post-metadata">

**Author:** ![richards](https://forum.bootstrapstudio.io/user_avatar/forum.bootstrapstudio.io/richards/32/3163_2.png) [@richards](https://forum.bootstrapstudio.io/u/richards)\
**Post date:** [October 12, 2024, 10:21am UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/11 "2024-10-12T10:21:26Z")

</div>

This js may be better for you and gets rid of needing to update the timestamps array each time.

you can set the first two lines of the code to suit your sites layout

articlesUrl will be set to the url of your articles index page  
messageElement will be the element to display the message.

This is based that each article on the articles page has a class of .article

```auto
document.addEventListener("DOMContentLoaded", () => {
  const articlesUrl = "articles.html";
  const messageElement = document.getElementById("articlesMessage");

  // Function to fetch the articles page and count the articles
  const checkArticlesCount = async () => {
    try {
      const response = await fetch(articlesUrl);
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }

      const parser = new DOMParser();
      const htmlDoc = parser.parseFromString(
        await response.text(),
        "text/html"
      );

      // Count the number of elements with class 'article'
      const currentCount = htmlDoc.querySelectorAll(".article").length;

      // Retrieve the previous count from local storage
      const previousCount = localStorage.getItem("articleCount");

      // Compare the counts and display a message if needed
      if (previousCount) {
        const newArticlesCount = currentCount - previousCount;

         if (newArticlesCount == 0) {
           messageElement.textContent = `There are no new articles since your last visit.`;
         }

        if (newArticlesCount == 1) {
          messageElement.textContent = `There is a new article for you since your last visit.`;
        }

        if (newArticlesCount > 1) {
          messageElement.textContent = `There are ${newArticlesCount} new articles since your last visit.`;
        }
      }

      // Store the current count in local storage
      localStorage.setItem("articleCount", currentCount);
    } catch (error) {
      console.error("Error fetching articles:", error);
    }
  };

  // Check articles count on page load
  checkArticlesCount();
});

```

---

<div class="post-metadata">

**Author:** ![parmaster](https://forum.bootstrapstudio.io/letter_avatar_proxy/v4/letter/p/df788c/32.png) [@parmaster](https://forum.bootstrapstudio.io/u/parmaster)\
**Post date:** [October 12, 2024, 11:15am UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/12 "2024-10-12T11:15:10Z")

</div>

Thank you for your work and your help!

But I don’t get it.

Where should I mark the article as an article? Do I need to use the bootstrap component (html 5 article) and wrap it around the complete article (it has divs, etc), or do I need to add .article to each div (every div in the first level is a new article in my case).

And is this right with the articlemessage?

Where should the message appear that there is none, one or more new articles?

 ![article](https://forum.bootstrapstudio.io/uploads/default/original/2X/f/fa29325cf1dc612b1502a8a215fa0cb60127eac5.png)  
 ![article2](https://forum.bootstrapstudio.io/uploads/default/original/2X/6/65d9c9bcdd71fc656c32546333bf8a82a18142c4.png)  
 ![article3](https://forum.bootstrapstudio.io/uploads/default/original/2X/1/153ea36268f31699b5697abaf5d1117927a0c4c1.png)

---

<div class="post-metadata">

**Author:** ![richards](https://forum.bootstrapstudio.io/user_avatar/forum.bootstrapstudio.io/richards/32/3163_2.png) [@richards](https://forum.bootstrapstudio.io/u/richards)\
**Post date:** [October 12, 2024, 12:57pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/13 "2024-10-12T12:57:19Z")

</div>

here is the bss file so you can see all the structure.

[https://dropover.cloud/4917af](https://dropover.cloud/4917af)

I have updated the script and tried to comment as much as possible so you can see what is going on.

---

<div class="post-metadata">

**Author:** ![parmaster](https://forum.bootstrapstudio.io/letter_avatar_proxy/v4/letter/p/df788c/32.png) [@parmaster](https://forum.bootstrapstudio.io/u/parmaster)\
**Post date:** [October 12, 2024, 4:19pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/14 "2024-10-12T16:19:46Z")

</div>

Thank you very much for your example file.

Now everything is clear to me and I know what you meant.  
The example is really great.

---

<div class="post-metadata">

**Author:** ![parmaster](https://forum.bootstrapstudio.io/letter_avatar_proxy/v4/letter/p/df788c/32.png) [@parmaster](https://forum.bootstrapstudio.io/u/parmaster)\
**Post date:** [October 13, 2024, 1:08pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/15 "2024-10-13T13:08:58Z")

</div>

One last question:

My Navbar is “fixed to top”.  
Of course I could set the “Header-\>Div with the article count” with a margin under the Navbar or to another location (under my Navbar is a hero banner).

Is there a better way to set it without to move everything?

EDIT:  
And if there are no new articles there shouldn’t be show anything.

EDIT:

Please forget my first question.  
I will try to show a modal. 🙂

---

<div class="post-metadata">

**Author:** ![richards](https://forum.bootstrapstudio.io/user_avatar/forum.bootstrapstudio.io/richards/32/3163_2.png) [@richards](https://forum.bootstrapstudio.io/u/richards)\
**Post date:** [October 14, 2024, 9:10am UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/16 "2024-10-14T09:10:29Z")

</div>

You can have the message appear in any element on your page, just give it an ID of “articlesMessage” (or change the id on line 3 of the JS in the example to suit)

To not show a message when there are no new articles comment out lines 30 and 42 in the JS

The example also includes this CSS, which will hide the message element when it has no contents

```auto
#articlesMessage:empty {
  display: none;
}

```

---

<div class="post-metadata">

**Author:** ![parmaster](https://forum.bootstrapstudio.io/letter_avatar_proxy/v4/letter/p/df788c/32.png) [@parmaster](https://forum.bootstrapstudio.io/u/parmaster)\
**Post date:** [October 14, 2024, 3:07pm UTC](https://forum.bootstrapstudio.io/t/badge-in-navbar/11719/17 "2024-10-14T15:07:39Z")

</div>

Thank you for your answer!

After I wrote here yesterday I tried a lot of options ( and saw the css part) on how I will use it and tested many things.

I still can’t decide how I’m going to use it. 🙃
