1

I need help creating a simple if else statement that will help us track outbound links.

The goal is to return a true or false (or 1 or 0) whenever the URL being clicked matches the current hostname/domain. Here's what I have so far:

<script>
function myFunction()
{
var x = document.getElementsByTagName("A")[0].hostname;
var y = location.hostname;
    if (x=y) {
        return 1;
    } else {
        return 0;
    }
}
</script>

Obviously I have no idea what I'm doing, so I appreciate the help. I'm eventually going to be using this as a macro in Google Tag Manager for tracking outbound links.

Thanks,

MMMdata
  • 817
  • 8
  • 19
  • As @crypticous said, you can't use a single `=` to compare. A single `=` is an assignment statement; as written, you are assigning the value of `y` to the variable `x`. Use one of the comparison operators `==` or `===`. Here's how they're different: http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons – Katie Kilian Mar 13 '14 at 18:57

1 Answers1

4
function myFunction(){
    var x = document.getElementsByTagName("A")[0].hostname;
    var y = location.hostname;
    return x === y; // returns true/false
}

In if statement two or three equal are for comparisons, not one

= assignment == equality === strict equality ( type )

nanobash
  • 5,419
  • 7
  • 38
  • 56