Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide div if URL contains word

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

like image 577
Ashton Williams Avatar asked Jul 11 '12 15:07

Ashton Williams


People also ask

How do I hide a div section?

The document. getElementById will select the div with given id. The style. display = "none" will make it disappear when clicked on div.

How do I hide a div if there is no content?

Hide empty divs - To hide the div set: display: none; in :empty selector · GitHub.

How do I hide a specific div in HTML?

To hide a div using JavaScript, get reference to the div element, and assign value of "none" to the element. style. display property.


2 Answers

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"

like image 182
Joe Avatar answered Sep 21 '22 02:09

Joe


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.

like image 2
Dylan Douglas Avatar answered Sep 20 '22 02:09

Dylan Douglas