views:

50

answers:

3

so I have a javascript function that changes the class name of a div

function flip (event)
{
  var element = event.currentTarget;
  element.className = (element.className == 'card') ? 'card flipped' : 'card';
}

How can I make it so my onclick="flip(event)" can be attached to a button (or preferably an image) and the button will then flip the card instead of just clicking inside the div. So something like

<div id="card" class="card">
  <p>
    whatever
  </p>
<img onclick="flip(event)" src="foo">
</div>

What do I need to change in my javascript function?

+1  A: 

This should work

<img onclick="javascript:flip('card');" />

function flip (elementId) 
{ 
  var element = document.getElementById(elementId)
  element.className = (element.className == 'card') ? 'card flipped' : 'card'; 
} 
John Hartsock
fantastic! worked like a charm!
jtmkrueger
A: 
sushil bharwani
the question does not specify jquery.
John Hartsock
A: 

the event object has a reference to the element that originated the event. you can use parentNode to work back up the tree.

this will work with your html example.

function flip (event)
{
    var image = event.target || event.srcElement;
    var div = image.parentNode;
    div.className = (div.className == 'card') ? 'card flipped' : 'card';
}

target is the originating element in ff/chrome, srcElement is the same element in IE. currentTarget in ff/chrome is the element which called the handler, which may not be the same element you clicked on. for example, if you attached a click handler right on the div, it would fire when you clicked on the image within. when the div's handler fires, currentTarget would be the div and target would be the image. IE has no parallel for currentTarget that i'm aware of.

lincolnk
well... IE's Lack of parallel's never seems to end! This was very informative. I'm sure by the nature of my question it's apparent that I have alot to learn about javascript. This helps me understand how my fix worked. Cheers!
jtmkrueger