I'm using this javascript code to have a couple "show/hide" toggled divs on my site:
<script language="javascript">
function toggledean() {
var ele = document.getElementById("toggleTextdean");
var text = document.getElementById("displayTextdean");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "Show more";
}
else {
ele.style.display = "block";
text.innerHTML = "Hide";
}
}
</script>
What should I add to this code to have the div be displayed upon loading the page with a specific #hash added to the URL?
Thank you very much.
This is not the javascript answer that you want, but you could try playing around with the :target
pseudo selector. For instance,
<!-- HTML -->
<div id="foo">show this with #foo.</div>
<div id="bar">#bar shows this.</div>
<style type="text/css">
div {display: none}
:target {display: block}
</style>
Example: http://jsfiddle.net/ZAHns/4/ (thanks to Jared for the idea of adding the anchors).
Depending on what you are trying to do, this could possibly work, but think your requirements through.
Note: Take this response with a HUGE grain of salt -- don't use it.
To answer the actual question, use the following to determine if the hash is present:
var in_hash = location.hash.slice(1) === what_you_are_looking_for;
if (in_hash) ? /* IN HASH */ : /* NOT IN HASH */;
Something like this should work:
<script>
var hash = window.location.hash.replace('#', '');
if (hash) {
document.getElementById(hash).style.display = 'block'
}
</script>
If you've only got the one element, like your script has, you could just call the function to toggle it if any hash exists in the url:
<script type="text/javascript">
function toggledean() {
...
}
if (window.location.hash == '#dean') toggledean();
</script>
Or you could make your toggle script a little more universal:
<script type="text/javascript">
var hash = window.location.hash.replace('#', '');
function toggle (elementPartial) {
var ele = document.getElementById('toggleText'+elementPartial);
var text = document.getElementById('displayText'+elementPartial);
if(ele.style.display == 'block') {
ele.style.display = 'none';
text.innerHTML = 'Show more';
} else {
ele.style.display = 'block';
text.innerHTML = 'Hide';
}
}
if (hash) {
toggle(hash);
}
</script>
Additionally, you could make this a little simpler and more flexible using a javascript framework, like jQuery.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With