0

I try to grab the url path and then add active class on li example: www.mysite.com/?p=xxxx

the x will change depending on which link the user clicks on

I tried this:

<ul class="top_menu">
<li class="tider"><a href="/?p=1884">Åbningstider</a></li>
<li class="butikker"><a href="/?p=1885">Butikker</a></li>
<li class="sker"><a href="/?p=1886">Det sker</a></li>
<li class="nyhedsbrev"><a href="/?p=1887">Nyhedsbrev</a></li>
<li class="vej"><a href="/?p=1888">Find vej</a></li>
</ul>

var text = window.location.href.match(/http:\/\/www\.mysite\.com\/(.+)/)[1].replace(/_/g,' ');
$("#nav li").filter(function() {
  return $.text([this]) == text;
}).addClass("active");

but nothing happens. What im i doing wrong?

1
  • firstly you could just use window.location.search, to skip the regex part Commented Aug 2, 2012 at 7:43

3 Answers 3

7

This works!

$(document).ready(function(){

    var full_path = location.href.split("#")[0];

    $(".top_menu li a").each(function(){

        var $this = $(this);

        if($this.prop("href").split("#")[0] == full_path) {

            $(this).parent().addClass("active");

        }

    });

});
Sign up to request clarification or add additional context in comments.

Comments

1

You could use the ends with attribute selector:

var pid = '1885'; //Get the current value of p
$('#nav li a[href$="'+pid+'"]').parent().addClass('active');

This will get the link where the href attribute ends in pid (in this case 1885).

That will lead to problems if you have 2 values that end in the same string (like p=1885 and p=11885).

3 Comments

Could you explain a littel bit more? Im not that skilled in jq
Then i will have to make one for each link ?
No, just once but you'll have to replace the first line with the current value for p. I recommend using document.location.search and running a regex on that.
0

What about changing class names and use PHP and jQuery:

<?php

if(isset($_GET['p'])) {

    echo '<script type="text/javascript">
    $(document).ready(function(){';

    $from_url = $_GET['p'];

    echo '
    $(\'p_' . $from_url . '\').addClass(\'active\');
        });
    </script>';
    }

?>

For example, at "www.mysite.com/?p=1888" the above will print:

<script type="text/javascript">
$(document).ready(function(){
    $('.p_1888').addClass('active');
    });
</script>

It will add class "active" for the HTML with class name "p_1888". For example:

<li class="p_1888"><a href="/?p=1888">Find vej</a></li>

Also explained here.

1 Comment

Good idea, but the site is written in aspx. And i have no experience in aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.