Question

I'm using blade template, the template contains a navigation bar. it is something like this

<ul>
    <li class="active"><a href="page1">page1</a></li>
    <li><a href="page1">page1</a></li>
    <li><a href="page1">page1</a></li>
</ul> 

Using jquery I can make the li element active once clicked. Now the problem is when I click on the second link the page2 will be loaded and that page extends the same template so it will load it again and there then the 1st element will be active. The solution that I thought about is adding a div to each page to let me identify the page

<div class="type" data-type="page2"></div> 

and when the page is loaded I set the selected li element depending on the page type. I try this and it is working the only thing is that I don't think it is the perfect solution. Is there an other more simple way to solve this? Thanks

Was it helpful?

Solution

I'd set a class on the html element to identity your page. That way you can have javascript as well as css react to what type of page you're on. Not that you need css in this particular example, but down the line use-cases might pop-up and then you already have a solution in place.

edit:

Adding class dynamically through a tiny script:

    //script in specific page
    <script>pagetype = "page2"</script>

    //script as part of layout template shared between pages
    <script>
    $(function(){
      $("html").addClass(pagetype);
    })
    </script>

OTHER TIPS

In my opinion, a better solution would be detecting the current page with Request::segment() (or Request::is(), depending on the stucture of your URLs) method. Combine that with a View composer to avoid passing data to each view manually.

An example:

The view composer:

class PageComposer
{
    public function compose($view)
    {
        $view->with('active', Request::segment(1));
    }
}

The service provider:

class PageServiceProvider extends ServiceProvider
{
    public function register()
    {
        View::composer('partials.header', 'PageComposer');
    }
}

The part of the header file that is common to all your pages:

<ul id='pages'>
    <li id='page1'><a href="page1">page1</a></li>
    <li id='page2'><a href="page2">page2</a></li>
    <li id='page3'><a href="page3">page3</a></li>
</ul>

The script that changes the active class:

<script>
    $(document).ready(function () {
       var activeLink = $('#{{ $active }}');               
       activeLink.addClass('active');
    });
</script>

More information about this in Laravel 4 documentation:

Requests

View Composers

You can compare anchor href to pathname and then add style or assign class to correct anchor e.g

...

<li><a href="index.php">Link</a></li>

...

$('a[href="'+window.location.pathname.split('/').pop()+'"]').css({ color: 'red' });

or

$('a[href="'+window.location.pathname.split('/').pop()+'"]').addClass('current');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top