ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Can EE evaluate a final hash segment of a URL?

November 10, 2009 5:02pm

Subscribe [2]
  • #1 / Nov 10, 2009 5:02pm

    spacewalk

    106 posts

    I have some sub-navigation on a page that uses hrefs containing a hash (for example, #something) to scroll to divs with specific IDs in the page. So… I could have a URL like this:

    <a href="http://www.domainname.com/index.php/portfolio/category/corporate/#some-div-on-the-page">http://www.domainname.com/index.php/portfolio/category/corporate/#some-div-on-the-page</a>

    Sometimes I hit such URLs from a link somewhere else, without the user directly clicking on the page’s sub-navigation. Or a user might bookmark a URL containing a hash. When that happens, I want to add a CSS class to the sub-nav anchor to highlight it in “you are here” fashion. I do this all the time in EE by using URL segments, such as:

    {if segment_3 == "corporate"} class="active" {/if}

    But segments don’t work for that final URL hash element. In the above URL example, {segment_3} == “corporate” but {segment_4} is empty.

    Any way to compare the URL hash segment during page processing? If not a native EE way, a PHP technique? Those are preferred, in that order, because I’d rather do this on the server than with jQuery.

    But if I absolutely have to do it with jQuery, I know can get the hash with window[dot]location[dot]hash. However, I don’t know my JQuery well enough to traverse the DOM until I find an anchor with an href that matches the URL hash.

    Thanks.

  • #2 / Nov 10, 2009 6:29pm

    Ponder The Web

    20 posts

    You can get the hash in javascript with

    if(location.hash){
        var loc = location.hash.substr(1,location.hash.length);
    }

    or you can do it in php with parse_url
    http://php.net/manual/en/function.parse-url.php

  • #3 / Nov 10, 2009 9:07pm

    spacewalk

    106 posts

    Thanks for the answer. I ended up doing it with jQuery. For future readers:

    //requires jQuery
                    //highlight the proper navigation item when a url hash causes a scroll to an id or name
                    var theHash = location.hash;
                    $('ul#nav-list a').filter(function() {
                        return $(this).attr("href") == theHash; //find the anchor whose href equals theHash
                    })
                    .addClass("you-are-here"); //add the "you-are-here" class to that anchor
.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases