Search code examples
javascriptjqueryflaskjinja2

Changing active class when clicking on new page without refreshing


I am implementing a flask app with Jinja templating, and I am trying to add an active class to one of my nav anchor elements at a time, based on which URL the user is currently on. However, this is only working when I load the home page or refresh any page, but not when I click a different page.

I have tried many approaches using plain JavaScript, jQuery, and jinja templating to solve this issue, but all of them produced the same result that I have mentioned.

Here's my application.py file

@app.route("/")
def index():
   return render_template("index.html", page="")


@app.route("/AboutUs")
   def about():
   return render_template("about.html")


@app.route("/Services")
def services():
   return render_template("services.html")

Here's code for the navigation menu in my layout html template:

<div class="navbar-nav mx-auto" id="menu">
  <a {% if request.path == '/' %}class="active nav-link"{% endif %}
  class="nav-link" href="/">Home</a>
  <a {% if request.path == '/AboutUs' %}class="active nav-link"{% endif %}
  class="nav-link" href="/AboutUs">About Us</a>
  <a {% if request.path == '/Services' %}class="active nav-link"{% endif %}
  class="nav-link" href="/Services">Our Services</a>
</div>

Could someone direct me to where the problem could be?


Solution

  • In my project i have use below code to make it work . You can just check if the path given has in request.path or not depending on this add active . i.e :

      <div class="navbar-nav mx-auto" id="menu">
          <a {% if request.path == '/' %}
                class="active nav-link"
             {% else %}
                class="nav-link"
             {% endif %}
            href="/">Home</a>
          <a {% if '/AboutUs' in request.path %}
              class="active nav-link" 
            {% else %}
             class="nav-link"
            {% endif %} 
            href="/AboutUs">About Us</a>
          <a {% if '/Services' in request.path  %}
             class="active nav-link" 
            {% else %}
          class="nav-link"
            {% endif %} href="/Services">Our Services</a>
        </div>