0

I can't find out why this is not working:

var myurl = "http://domain.com";
var currenturl = $(location).attr('href');
if (myurl == currenturl) {
...

Both myurl and currenturl are the same, yet the script in the if statement is not get executed.

EDIT:

$(document).ready(function(){
var myurl = "http://domain.com";
var currenturl = window.location.href;
//alert(currenturl);
    if (myurl === currenturl) {
        alert('should see this');
    } else {
    }
});

SOLUTION:

$(document).ready(function(){
var myurl = "http://domain.com/"; // see the slash at the end
    if (myurl == location.href) {
        alert('that ss the same page');
    } else {
    }
});

Any suggestion? Thans.

elbatron
  • 675
  • 3
  • 16
  • 30

2 Answers2

4

You don't have to use jQuery for it, just:

if (myurl == location.href) {
    // the same
}

If that doesn't work, make sure they're both the same by debugging their values:

console.log(myurl, location.href);
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

That doesn't work anyway, because you can't compare objects in JavaScript like that. The fact that $(location) is almost certainly undefined will be a problem. See: Object comparison in JavaScript

If you are using a local file, you should add "file://" to the URL

<html>
<script src="https://www.google.com/jsapi"></script>
<script>
google.load('jquery', '1.7.2');
</script>

<script>

$(document).ready(function(){
var myurl = "file://somedir/test.html";
var currenturl = window.location.href;
//alert(currenturl);
    if (myurl === currenturl) {
        alert('should see this');
    } else {
        alert ('see other thing');
    }
});


</script>
<body>
hi
</body>
</html>
Community
  • 1
  • 1
Michael Manoochehri
  • 7,931
  • 6
  • 33
  • 47
  • Actually, `$(location).attr('href')` does work ... not sure how cross-browser it is though; doesn't take away the fact that it's just plain silly – Ja͢ck May 27 '12 at 07:58
  • I just tried it with `$(location).attr('href')` and it works, also tried with `location.href` and that works as well. – elbatron May 27 '12 at 08:08