user3008711
user3008711

Reputation: 33

Jquery onclick, but do action after page reload

I use Twitter/Bootstrap navbar and i want to add the class "active" dynamically.

There is a Jquery code which is supposed to do that: My problem: It adds the class "active" but it's also a link so the pages is going to be reloaded and the code loses its effectivness.

$(document).ready(function() {
    $(".nav li").click(function() {
        $(this).addClass("active");
    });
});

There are 5 elements. The click is working and it adds the class but the link in the LI is not working any more besides that it should remove the class active and should add it to the new one

Upvotes: 0

Views: 4107

Answers (3)

Blair Anderson
Blair Anderson

Reputation: 20161

DO NOT USE COOKIES. Your page is reloading!

Instead of using a cookie to remember which link you clicked, you should just check if the links in the nav are the same as the current url, and if they're the same then add an active class.

$(document).ready(function(){
  $(".nav li").each(function(){
    var href = $(this).find('a').attr('href');
    if (href === window.location.pathname) {
      $(this).addClass('active');
    }
  });
});

this will run after your page reloads but it will be fine!

the problem with cookies is that someone will click a link, then go away and come back but your cookies will show them the incorrectly active link(because the cookie stored it!!!)

Upvotes: 2

mplungjan
mplungjan

Reputation: 177786

If your LI has a link in it try this

NOTE: If you DO reload, you will need a cookie or set the hash to remember the state of the active link

Live Demo

$(function() {
    $(".nav li").click(function(e) {
      if (e.target.nodeName == "A") {
          e.preventDefault();
      }
      $(this).siblings().removeClass()
      $(this).addClass("active");
  });
});

With cookie functionality:

$(function() {
    $(".nav li").on("click",function(e) {
      if (e.target.nodeName == "A") {
          e.preventDefault();
      }
      $(this).siblings().removeClass()
      $(this).addClass("active");
      $.cookie("li",this.id);
  });
  var li = $.cookie("li");
  if (li) $("#"+li).addClass("active");
});

Upvotes: 2

Praveen M P
Praveen M P

Reputation: 11614

try this one

$("body").on("click",".nav li",function(){
        $(this).addClass("active");
});

this function will load after all the elements loaded

Upvotes: 0

Related Questions