Rita codes
Rita codes

Reputation: 33

Referencing `this` in inline event handlers

I want to be able to pass 'this' in a javascript 'mouseover'. I basically want to get the href from a link (that is unique) and pass it to every download button. But I get the error message:

undefined is not an object (evaluating 'this.getElementsByClassName('downLoad_link')[0].href = x)

Quite new to this so I hope anyone could help me! :)

Here is my code:

<a onmouseover="this.getElementsByClassName('downLoad_link')[0].href = 'www.example.com'" href="" class="downLoad_link" download>
    <button class="download">Download</button>
</a>

EDIT:

'www.example.com' will be replaced by a variable when I get to fix this issue!

Okay so my new code is this:

Javascript:

    <script type="text/javascript" language="javascript">
       var x = this.getElementsByClassName('getDownloadLink')[0].href; //this is not working!
    </script>

HTML:

<a onmouseover="this.getElementsByClassName('downLoad_link')[0].href = x" href="" class="downLoad_link" download>Download</a>

Upvotes: 0

Views: 135

Answers (2)

Willem van der Veen
Willem van der Veen

Reputation: 36630

I think this will answer your second question that you have.

var x = document.getElementById('getDownloadLink').href; //this is not working!
<a onmouseover="alert(x)" href="random" id="getDownloadLink">Download</a>

Here the value of the href gets put in the variable x. As an example I now changed the onmouseover as alert(x).

Upvotes: 1

xianshenglu
xianshenglu

Reputation: 5359

just use this not this.getElementsByClassName('downLoad_link')[0]

<a onmouseover="this.href = 'www.example.com'" href="" class="downLoad_link" download>
  <button class="download">
    Download
    </button>
</a>

Upvotes: 2

Related Questions