BobRock
BobRock

Reputation: 3467

jquery newbie onclick

If I'm in my view getting collection of images like this

foreach (var item in Model.Photos)
{
   <a href="@Url.Action("GetImage", "Property", new { id = item.Id })" >
      <img class="details" onclick="ImageDetails();" width="100" height="100"  src="@Url.Action("GetImage", "Property", new { id = item.Id })" />
  </a>        
}

This will reproduce html code, I'm sure you already know but here it is:

<a href="/Property/GetImage/5">
  <img class="details" width="100" height="100" src="/Property/GetImage/5" onclick="ImageDetails();">
</a>

I tried with my Photos.js like this, just for alert message

function ImageDetails() {
    $(".details").click(function (event) {
        alert('details alert');     
    });
}

No alert, no any message in firebug? Where did I wrong ?

Upvotes: 1

Views: 65

Answers (3)

Justin Morgan
Justin Morgan

Reputation: 30705

You're using jQuery's click binder incorrectly. You don't need to call that every time the control is clicked; you call it once, usually when the page loads. It's used to bind the control's onclick handler for all future clicks.

So you have two main options:

//HTML:
<img class="details" onclick="ImageDetails();" width="100" ...etc.

Or:

//HTML:
<img class="details" width="100" ...etc. (no onclick attribute)

//JavaScript:
$('.details').click(ImageDetails);

In either case, ImageDetails would be set up like this:

function ImageDetails(event) {
   alert('details alert');  
}

Upvotes: 0

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

Make sure you bind your events after the document has finished loading, or else the elements you're attempting to bind your events to won't have loaded yet.

$(function() {
    $(".details").click(function (event) {
        alert('details alert');     
    });
});

EDIT: Or you could just call ImageDetails() from the onload() function. :)

Upvotes: 1

alex
alex

Reputation: 490143

You should remove the onclick attribute in your HTML and either call ImageDetails() once or remove it from its function and just run it after the DOM is ready.

Upvotes: 0

Related Questions