0

I have an image that I want to execute a link with a javascript onClick event when the image is clicked.

The link is:

<a class="test" href="javascript:;" onclick="foo.add( 'name=name', 'quantity=1' );">
<img src="pic.png" alt="Click" /></a>

Jquery I am fiddling with

$('.test').click(function(){
onclick = $(this).attr('onclick');
$(this).attr('onclick','');
    return false;
});

Not working...

1 Answer 1

1

If you really want to just execute an already-existing onclick function, use something like this:

$('a.test img').click(function() {
  var link = $(this).parent()[0]
  var onclick = $(link).attr('onclick')
  onclick.call(link)
})

You want to pass the link into onclick.call. That sets the link as the receiver of the function call, which is how the onclick attribute would normally fire. If you simply call onclick(), you could run into trouble.

Sign up to request clarification or add additional context in comments.

2 Comments

It seems to do the onClick event but I get an error that onclick is undefined. Any ideas?
I'm not sure why you're getting the error you're getting. Here's a jsfiddle permalink to the example I was working with. jsfiddle.net/BrsmE . Does that help?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.