Reputation: 8415
Here's the suggested fiddle - http://jsbin.com/EzUTizuf/1/edit (because of the url navigation change the iframe from Codemirror JSBin goes to a blank page, which is why I didn't add a fiddle before)
I have an anchor navigating to #about. When the window.location is equal to #about I want to execute a small function corresponding to that specific window location.
This is the last code I tried to do this.
if (window.location.href === "#about") {
$('.about').show();
document.title="About";
alert("About DIV Shows Only From This URL!");
}
If anyone can help it'd be greatly appreciated.
Thanks!
Here's the full code.
<!DOCTYPE html>
<html>
<head>
<title>Grab DIV Hash</title>
<meta charset='utf-8'>
<meta name='viewport' content='initial-scale=1.0'>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.min.js'></script>
<style type='text/css'>
body {
position: absolute;
top: 0px; left: 0px;
width: 100%; height: 100%;
padding:0; margin:0;
background: #7abcff;
}
nav { text-align: center; }
a { outline: none; color: #000; text-decoration: none;}
a:hover { color: #555; }
a:active { color: #333; }
h1 {
margin-top: .25em;
font: bold 2.75em Arial, sans-serif;
text-shadow: rgba(0,0,0,0.5) -1px 0, rgba(0,0,0,0.3) 0 -1px, rgba(255,255,255,0.5) 0 1px, rgba(0,0,0,0.3) -1px -2px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('.about').hide();
function AboutPage() {
if (window.location.href === "#about") {
$('.about').show();
document.title="About";
alert("About DIV Shows Only From This URL!");
}
}
AboutPage();
});
</script>
</head>
<body>
<nav>
<a href="#about"><h1>About</h1></a>
</nav>
<div class="about">
1) About link clicked!<br />
2) This div should only be visible from whatever.com/#about
</div>
</body>
</html>
Upvotes: 1
Views: 73
Reputation: 94459
Within the conditional use window.location.hash
instead of window.location.href
to detect the value of the hash.
The code must also attach an event handler to window.onhashchange
to detect when the hash has changed. When the link is clicked jQuery's ready
event is not fired since a new page is not being loaded.
$(document).ready(function() {
$('.about').hide();
window.onhashchange = function(){
if(window.location.hash === "#about"){
$(".about").show();
document.title="About";
}
};
});
JS FIDDLE: http://jsfiddle.net/H6DZH/
Upvotes: 1