2

I'm doing this page with a lot of image links that change when the mouse hovers above them. I have a function for changing the image here:

    function hoverImg(element) {
        if (element.src.indexOf("_hover.png") == -1) {
            element.src = element.src.replace(".png","_hover.png");
        } else {
            element.src = element.src.replace("_hover.png",".png");
        }
    }

However, I have to give "this" as a parameter for the function on each onmouseover and onmouseout event for each element. Is there a way to just know what element called a function? Function copying isn't an option because, as I said, there'll possibly be a good hundred of these small images per page and the pages will be eventually generated from database data anyway. Adding "this" each time seems highly redundant...

Soulweaver
  • 23
  • 3

2 Answers2

2

Two options (onclick as example):

from html: onclick="javascript:hoverImg(this)"

or from code: x.onclick = hoverImg (this set okay now in callback because it is "invoked upon" the object in x later).

There are also some "behavior" JavaScript libraries (or even jQuery -- perhaps jQuery.live even) which may help you get what you want.

  • jQuery's live() was exactly what I was looking for - maybe even more; now I don't need to define the events for separate elements at all, just a single method for elements of a certain class is enough. Thanks! – Soulweaver Dec 18 '10 at 01:51
2

Try window.event.srcElement in your function. This assumes it's invoked directly from an event handler.

Hollister
  • 3,758
  • 2
  • 20
  • 22
  • Nice. Will work in IE -- but not sure if FF will buy it though (in the past it didn't support `window.event` IIRC). –  Dec 18 '10 at 02:48
  • Yes, that is IE only. Modern browsers use the `event.target` from the event parameter passed to the handler. It's been so long since I hand coded events like this without jQuery, I've grown dumberer. – Hollister Dec 18 '10 at 03:12
  • Chrome is OK with this. – Jerry Jun 08 '15 at 13:18