I need to hide a div if the url of the page contains a certain word. Thanks to this site I have been able to successfully find if the url contains the word. This code works:
<script type="text/javascript">
if (window.location.href.indexOf("Bar-Ends") != -1) {
alert("your url contains bar ends");
}
</script>
but for some reason it will not work to hide a div, like this:
<script type="text/javascript">
if (window.location.href.indexOf("Bar-Ends") != -1) {
$("#notBarEnds").hide();
}
</script>
<div id="notBarEnds">this is not bar ends</div>
Anyone have any idea what is wrong with this code? Any help is greatly appreciated Thanks
The document. getElementById will select the div with given id. The style. display = "none" will make it disappear when clicked on div.
Hide empty divs - To hide the div set: display: none; in :empty selector · GitHub.
To hide a div using JavaScript, get reference to the div element, and assign value of "none" to the element. style. display property.
Notice the reorder:
<div id="notBarEnds">this is not bar ends</div>
<script type="text/javascript">
if (window.location.href.indexOf("Bar-Ends") != -1) {
$("#notBarEnds").hide();
}
</script>
Or
<script type="text/javascript">
$(document).ready(function () {
if (window.location.href.indexOf("Bar-Ends") != -1) {
$("#notBarEnds").hide();
}
}
</script>
Waiting for the entire document to be "ready"
Try:
$(document).ready(function () {
if (window.location.href.indexOf("Bar-Ends") != -1) {
$("#notBarEnds").hide();
}
});
Your div hasn't necessarily loaded yet when the script runs.
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