Reputation: 61
I've been trying to find a short and easy to understand javascript that show a div based on the URL but all scripts I find doesn't seem to work.
I have this div on my page and the css file hides the div with: display:none;
<div id="idofthedivtohide"><span>Success!</span></div>
When I go to url: contact.php?success I want the div to change to display: block;
Can someone help me with this? Many examples make it work with like 4 lines of code.
I've tried this code but it doesn't seem to work:
<script type="text/javascript">
if (window.location.search.search(success)) document.getElementById("idofthedivtohide").style.display = "block"
</script>
Upvotes: 5
Views: 19357
Reputation: 65
We can execute this problem with this simple javascript function. To show a div based on the URL we can use the javascript 'window.location' object to get the current URL and then use an if statement to determine if the URL meets conditions to show or hide a div or any element.
function showDiv() {
if (window.location.href.indexOf("success") != -1) {
document.getElementById("idofthedivtohide").style.display = "block";
} else {
document.getElementById("idofthedivtohide").style.display = "none";
}
}
<body onload="showDiv()">
<div id="idofthedivtohide" style="display: none;">This is a div that will only be shown on the page where the page's URL contains "success" </div>
</body>
It will handle
contact.php?success
or
contact.php?!@#$success!@#$
Upvotes: 0
Reputation: 798
Here is another solution, more "human friendly":
HTML
<div id="idofthedivtohide">
<span>Success!</span>
</div>
JavaScript
<script type="text/javascript">
// Get URL
var url = window.location.href;
// Get DIV
var msg = document.getElementById('idofthedivtohide');
// Check if URL contains the keyword
if( url.search( 'success' ) > 0 ) {
// Display the message
msg.style.display = "block";
}
</script>
Upvotes: 5
Reputation: 206565
<div id="success"><span>Success!</span></div>
var locSearch = window.location.search.substring(1).split('&')[0];
if(locSearch){
document.getElementById( locSearch ).style.display = "block";
}
The above will handle
http://example.exm/page.html?success // success
same as
http://example.exm/page.html?success&user=2971024&votes=0 // success
Upvotes: 2