Bootstrap 3 nav-tabs active tab a current day of week

787 views Asked by At

How can I add class active to li a current day of the week?

<ul class="nav nav-tabs nav-justified responsive" id="myTab">
<li class="active"><a href="#resp-tab1">Monday</a></li>
<li><a href="#resp-tab2">Tuesday</a></li>
<li><a href="#resp-tab3">Wednesday</a></li>
<li><a href="#resp-tab4">Thursday</a></li>
<li><a href="#resp-tab5">Friday</a></li>
</ul>
2

There are 2 answers

0
noɥʇʎԀʎzɐɹƆ On

If you add active to the root <ul> element, all children will inherit the active class.

<ul class="nav nav-tabs nav-justified responsive active" id="myTab">
<li><a href="#resp-tab1">Monday</a></li>
<li><a href="#resp-tab2">Tuesday</a></li>
<li><a href="#resp-tab3">Wednesday</a></li>
<li><a href="#resp-tab4">Thursday</a></li>
<li><a href="#resp-tab5">Friday</a></li>
</ul>

You can do

li.active {
    /* your CSS goes here */
}

to only select li elements with the class active in your CSS.

1
avilac On

You can do it programatically using javascript, calculating the day and adding the "active" attribute to the element that contains the day of the week indicated.

Here you have the script i've been working so far:

HTML:

<ul class="nav nav-tabs nav-justified responsive" id="myTab">
<li name="Monday"><a href="#resp-tab1">Monday</a></li>
<li name="Tuesday"><a href="#resp-tab2">Tuesday</a></li>
<li name="Wednesday"><a href="#resp-tab3">Wednesday</a></li>
<li name="Thursday"><a href="#resp-tab4">Thursday</a></li>
<li name="Friday"><a href="#resp-tab5">Friday</a></li>
<li name="Saturday"><a href="#resp-tab4">Saturday</a></li>
<li name="Sunday"><a href="#resp-tab5">Sunday</a></li>
</ul>

As you can see, I added the name attribute to each li element. I do this because we're going to use them in our script below.

Javascript:

var d = new Date();
var weekday = new Array(7);
weekday[0] =  "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";

var n = weekday[d.getDay()];

var daysOfTheWeek = document.getElementsByTagName("li");

dayOfTheWeek(daysOfTheWeek);

function dayOfTheWeek (weekDays) {
    for(var i = 0; i < weekDays.length; i++)
  { 

    if(weekDays[i].getAttribute("name") == n)
    {
        weekDays[i].className = 'active';
      weekDays[i].childNodes[0].className = 'active';
    }
  }
}

Here, I created a Date object that will give us the name of the day of the week with the help of the weekday array. Once we have the name of the weekday, we call the dayOfTheWeek method, which will set active the elements we desire (the weekday of the list), turning its color into red (see CSS code below).

CSS:

li.active
{
  color: red;
}

a.active
{
  color: red;
}

Here we only created two rules to see what happens when we make our desired element active.

You can find my code here: https://jsfiddle.net/a0yjLc5z/6/

Hope it helps!