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
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
Share Improve this question asked Jul 11, 2012 at 15:53 Ashton WilliamsAshton Williams 531 gold badge1 silver badge3 bronze badges 3 |4 Answers
Reset to default 12Notice 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.
You're running an inline script as the HTML is being constructed, there isn't a div
named #notBarEnds
at the time that the script runs, you need to run it as a function after the document has loaded.
i write it without checking it, if doesn't work change de regex :D
$(document).on('ready', function()
{
if(window.location.href.match(/Bar\-Ends/i))
$("#notBarEnds").hide();
});
$('#notBarEnds')
is not prepared and you cannot invoke events against it. wrap this in$(function(){ //code })
– Ohgodwhy Commented Jul 11, 2012 at 15:55