Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting anchors with Jquery?

I want to know if it's possible to have the script detect the URL anchor, and load content specific to that anchor. For instance, I have this line of code:

<a href="#home"><span id="homeMenu">Home</span></a>

This line of code listens to this code:

$("#homeMenu").click(function () {
    $("#home_content").show("slow");
    $("#accommodations_content").hide("slow");
    });

How could I make it that if the user visits http://www.myurl.com/home.html#home that it loads the home content automatically. This should also work for all other anchors that I would want to implement.

I want this because, right now, if the user visits any of the anchors directly, no mater which anchor, it will always display the home page. So, is there a way to detect which URL is loaded and then run a script on that?

EDIT

So,currently it ONLY loads accommodations (even when on the #Home)

Current code:

 <script type="text/javascript"> 
            $(document).ready(function() {
            document.getElementById("javascriptCheck").style.visibility = 'hidden';
            $("#menu").load("snippets/menu.html");
            $("#locationMenu").load("snippets/locationMenu.html");
            $("#home_content").load("snippets/home_content.html");
            $("#accommodations_content").load("snippets/accommodations.html");
            $("#history").load("snippets/history.html");
            $("#footer").load("snippets/footer.html");

            var hash = window.location.hash;
            if (hash = "#Home") {
                $("#home_content").show("slow");
                $("#accommodations_content").hide("slow");
            }
            if (hash = "#Accommodations") {
                $("#accommodations_content").show("slow");
                $("#home_content").hide("slow");     
            }
            } );
        </script> 
like image 616
Hanna Avatar asked Dec 04 '22 23:12

Hanna


2 Answers

You have to check for hash tags on page load.

use this code:

var identifier = window.location.hash; //gets everything after the hashtag i.e. #home

if (identifier === "#home") {
     $("#home_content").show("slow");
     $("#accommodations_content").hide("slow");
}
like image 81
switz Avatar answered Dec 12 '22 10:12

switz


I guess, you want something like this: jQuery hashchange plugin. It allows you to react to changes to the hash and load for example other content via AJAX - but you can do other stuff as well. The user even can use the back & forward button of the browser to go to a previous state.

like image 26
iGEL Avatar answered Dec 12 '22 09:12

iGEL