0

I want to add class in link if previous link was home link i am trying so hard but I am not getting the answer of it. it is simple nav bar, if active link home then clicked link will be added a class..thats it

$('ul li').click(function(){
    var prevLink = ??; // how can i get prevLink here
    if(prevLink == 'Home') {
        $(this).addClass("addext");
        $('ul li').removeClass("addext");
    }
});

how to check previous active link ?

Vishal B
  • 653
  • 2
  • 12
  • 31

3 Answers3

1

Not the complete answer, because of your missing html, but you should switch these two lines:

$(this).addClass("addext");
$('ul li').removeClass("addext");

To:

$('ul li').removeClass("addext");
$(this).addClass("addext");

Otherwise you set, and instant remove the class.

eisbehr
  • 12,243
  • 7
  • 38
  • 63
1

Hope this will help:

var globalPrevLink = "";

$('#Home').onclick(function(){
    globalPrevLink = window.location.href; // this is clicked last time so remember it in globalPrevLink variable
});

Put above code somewhere in your js and change Home to whatever ID you have given to your home link tag.

then change your code as

$('ul li').click(function(){
    var prevLink = globalPrevLink; // globalPrevLink is assigned here
    if(prevLink == 'Home') { // change this also as accordingly, use console log
        $('ul li').removeClass("addext"); // switch as suggested in other comment
        $(this).addClass("addext");
    }
});
Irfan Anwar
  • 1,878
  • 17
  • 30
  • it should be automatically check the active link among the unordered list. if thet link is home link then next line will exicute.. – Vishal B Aug 02 '16 at 13:18
  • I can give hint to you only but you'll have to find it by yourself – Irfan Anwar Aug 02 '16 at 13:21
  • You should create a common method that should be called on each unordered list item clicked – Irfan Anwar Aug 02 '16 at 13:22
  • use this link to know how you can call same function on different buttons http://stackoverflow.com/questions/18410341/using-multiple-buttons-on-same-function-that-redirects-to-different-functions – Irfan Anwar Aug 02 '16 at 13:24
0

Use $('ul li.addext').text(); to get the li text which has addest class

$('ul li').click(function(){
        var prevLink = $('ul li.addext').text();
        if(prevLink == 'Home') {

             $('ul li').removeClass("addext");
            $(this).addClass("addext");

        }
    });
Amar Singh
  • 5,464
  • 2
  • 26
  • 55