Detecting anchors with Jquery?
Solution 1
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");
}
Solution 2
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.
Hanna
Updated on June 20, 2022Comments
-
Hanna almost 2 years
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>
-
Hanna about 13 yearsFor some reason I'm having issues with this code. Where exactly should it go?
-
Hanna about 13 yearsOk, that's why I did, it doesn't load right. I posted my code and the issue above.
-
Hanna about 13 yearsOk, I found out what was broken about the code, and I feel like a huge idiot.
if (identifier = "#home")
should beif (identifier == "#home")