Reputation: 251
I have set up a custom homepage that links to a few bookmarks like Google or Wikipedia.
The links are set up as a
elements that contain the specific site's href
. Within the a
element, I put a div
with class="clickArea"
and onmouseover="overClickArea('page-description')"
, which displays a short description in some other div
(that works fine).
Also, it should actually set the content of my own custom search bar (within the site) to the value of the href
attribute of the parent a
tag. The search bar is an input
element.
To get that href
value, I use parentNode
and getAttribute('href')
on the this
pointer. The parentNode
function returns undefined
though.
I am aware of the this
pointer referring to the element that the function is a method of.
I have unsuccessfully tried to replace this
with div
and to pass this
as a function parameter.
I'd be glad to get that one done, thanks a lot for any help :)
One of the links:
<a href="http://de.wikipedia.org/wiki/Wikipedia:Hauptseite">
<div class="clickArea" onmouseover="overClickArea('Wikipedia - The Free Encyclopedia')">
<img class="icon" src="Icon_Wikipedia.png" alt="Wikipedia" />
<br>Wikipedia
</div>
</a>
JavaScript function:
function overClickArea(descStr){
document.getElementById('description').innerHTML = descStr;
var url = this.parentNode.getAttribute('href');
document.getElementById('searchbar').value = url;
}
Upvotes: 0
Views: 1263
Reputation: 5226
Just to expand on Quentins Answer, to access the element , instead of using this
in your function ( which references the function itself ) you need the event.target
and that is best passed in from your mouseover handler
onmouseover="overClickArea(event,'Wikipedia - The Free Encyclopedia')"
Then, in your function accept it and you can get the this you are after
function overClickArea(event,descStr){
event = event || window.event;
var url = event.target.parentNode.getAttribute('href');
....
Upvotes: 1
Reputation: 940
this
refers to the window object, so it does not have a parent node. Change it
<div class="clickArea" onmouseover="overClickArea(this,'Wikipedia - The Free Encyclopedia')">
and :
function overClickArea(source, descStr){
document.getElementById('description').innerHTML = descStr;
var url = source.parentNode.getAttribute('href');
document.getElementById('searchbar').value = url;
}
Upvotes: 1
Reputation: 944526
You call overClickArea
like this:
onmouseover="overClickArea('page-description')"
Since you haven't specified a context, it will be called in the context of the default object. In a browser, that is window
.
You seem to be assuming that it will be the element the onmouseover
attribute is attached to. It isn't.
window
doesn't have a parentNode
property (at least by default).
Inside the event handler function itself (i.e. onmouseover="this"
), this
will be that element.
Upvotes: 2