Logan Kling
Logan Kling

Reputation: 589

Variable not being set correctly; how to fix?

I want my JQuery to select one of the navigation links—based on the page that I'm on—and then I want it to move it to the top of the list.

This is the HTML of my navigation bar:

<nav>
    <ul id=nav>
        <li><a href="index.php">Home</a></li>
        <li><a href="skillsets.php">Skillsets</a></li>
        <li><a href="gallery.php"><icon>Gallery</a></li>
        <li><a href="about.php">About</a></li>
        <li><a href="contact.php">Contact</a></li>
    </ul>
</nav>

This is the JQuery I'm using to try and reorder the list:

var page = document.location.pathname.match(/[^\/]+$/)[0];
$(document).ready(function(){
    var ul = $('nav').children('ul'),
        li = ul.children('li'),
        href = $('a[href*='+page+']');
        //move element to top
        ul.prepend(href.parent());
});

It isn't working and I would assume that it's because the href variable isn't being set correctly. alert(href); and alert(href.parent()); output nothing.

Any ideas? Thanks!

Upvotes: 0

Views: 86

Answers (3)

Dimag Kharab
Dimag Kharab

Reputation: 4519

Try this, it will work.

<script>
    var page = document.location.pathname.match(/[^\/]+$/)[0];    

    $(document).ready(function()
    {
            var href = $('a[href='+'"'+page+'"'+']').parent();
            var parent = $("#nav");    
            var childToMoveLast = href.remove();
            parent.prepend(childToMoveLast);

    });

 </script>

Here is the HTML

<nav>
    <ul id='nav'>
        <li><a href="index.php">Home</a></li>
        <li><a href="skillsets.php">Skillsets</a></li>
        <li><a href="gallery.php"><icon>Gallery</a></li>
        <li><a href="about.php">About</a></li>
        <li><a href="contact.php">Contact</a></li>
    </ul>
</nav>

Upvotes: 0

Shuhei Kagawa
Shuhei Kagawa

Reputation: 4777

var href = $('a[href*="'+page+'"]');

EDIT

Also, you can write a bit shorter with child selectors:

var ul = $('nav > ul'),
    href = ul.find('> li a[href*="' + page + '"]');
ul.prepend(href.parent());

Upvotes: 0

Y.Puzyrenko
Y.Puzyrenko

Reputation: 2196

As @user3064914 said, you missed '#', but you missed quotes either:

<ul id = "nav">

Upvotes: 1

Related Questions