JulenissensHjelper
JulenissensHjelper

Reputation: 969

Javascript: Receiving onClick on top of image inside a div, can it be done?

I basically have a div set up with an onClick action like so:

myDiv.setAttribute("onclick", myAction);

And later on, I place an image inside the div like this:

myDiv.innerHTML = '<img src="' + myImage + '" height="' + myDiv.height + '" width="' + myDiv.width + '">';

.width and . height are properties I have created for myDiv.

So my problem is that when I place the image inside the div, myDiv's onClick is not responding, is there anyway to solve this. I know of the div property backgroundImage, but that one does not support customizing of size in all browsers. I tried to give the image the same onClick action that the div has but that just got messy, is there any way to make javascript ignore the image and register a click in the div even though the click is in the image inside the div?

Visual explanation of the problem:

http://bildr.no/view/860258

Thank you.

Upvotes: 0

Views: 2032

Answers (4)

Naftali
Naftali

Reputation: 146310

I found your issue.

Here is the fiddle: http://jsfiddle.net/maniator/gN4e9/

The issue is on this line: myDiv.setAttribute("onclick", myAction);

That is placing the whole myAction function into the onclick which you don't want.

Change it to: myDiv.setAttribute("onclick", 'myAction()'); and it should work fine.

Upvotes: 0

Mark Costello
Mark Costello

Reputation: 4394

Rather than overwriting the innerHTML of the div, why not do something like this?

var img = document.createElement('img');
img.setAttribute('src', myImage);
img.setAttribute('width', myDiv.width);
img.setAttribute('height', myDiv.height);
myDiv.appendChild(img);

Upvotes: 2

S Pangborn
S Pangborn

Reputation: 12739

Yes, and what you're looking for is event propagation. A JS library like jQuery might be really helpful for something like this. jQuery uses a .live() function to accomplish event propagation.

For the given HTML:

<div class="imageWrap">
    <img src="someimage.jpg">
</div>

You would use something like:

$(".imageWrap").live("click", function (event) {
    // Do something awesome here
    $(event.target).addClass("clicked");
});

The click on the image should "propagate" or bubble up to the div, where it can be caught and processed. Event bubbling is incredibly useful once you get the hang of how it works.

Upvotes: 0

NKCSS
NKCSS

Reputation: 2746

First thing I thought of was Don't events bubble up? I started searching and turned up this. I think that might be an interresting read.

Upvotes: 0

Related Questions