Peter
Peter

Reputation: 14508

JQuery - Add onclick to dynamically generated img tag

I am creating several image dynamically using the following code:

function refresh_gallery(galleryidentifier, albumid) {
    $.ajax({ type: "POST", url: "/Photos/Thumbnails/" + albumid + "/", data: {}, success: function(msg) {
        try {
            var fotos = eval(msg); $(galleryidentifier).empty(); if (fotos.length == 0) { $(galleryidentifier).html("Press "Add files..." and select files to upload!"); return true; }
            for (var f in fotos) {
                //this image needs the onclick eventhandler
                $(document.createElement("img")).attr({ src: '/images/delete.gif', title: 'Delete ' + fotos[f].Title }).addClass("icon_delete").appendTo(galleryidentifier); ;
                $(document.createElement("img")).attr({ src: fotos[f].ThumbnailPath, title: fotos[f].Title }).addClass("thumbnail").appendTo(galleryidentifier);
            }
            var del_div = $(document.createElement("div")).css({ "padding": "4px" }).appendTo(galleryidentifier);
            var delete_span = $(document.createElement("span")).click(delete_files(albumid)).css({ "cursor": "pointer", "font-size": "12px" }).appendTo(del_div);
            $(document.createElement("img")).attr({ "src": "/Content/images/delete.png" }).appendTo(delete_span);
            $(document.createTextNode("delete all")).appendTo(delete_span);
            return true;
        }
        catch (e) {
            alert(e);
        }
        alert("Refresh error!");
    }, error: function() { alert("Refresh error!"); }
    });
}

The generation of the images is working fine, but I want to add an onclick eventhandler to the first image being generated (see comment in code). How do I do this? I'm fairly new to JQuery.

Thanks!

Upvotes: 9

Views: 72855

Answers (5)

hitautodestruct
hitautodestruct

Reputation: 20820

Ever since jQuery 1.4 you can create an element and add all atrributes/events to it when creating.

In the case of an image tag you would write:

$('<img/>', {
    src:     '/images/delete.gif',
    title:   'Delete ' + fotos[f].Title,
    'class': 'icon_delete', // in quotes because class is a reserved js word
    click:   function( e ){
        // Everything here happens when you click the image.
    }
}).appendTo(galleryidentifier);

Above example in JSBin.

Here's the reference to the docs.

Why it's better than the other ways of creating an image using jQuery:

  • Much cleaner than chaining a dozen methods.
  • Allows you to send in objects with different properties to be created.
  • Matches up nicely with a regular html "Hard coded" element.

Upvotes: 6

Nadia Alramli
Nadia Alramli

Reputation: 114943

$(document.createElement("img"))
    .attr({ src: '/images/delete.gif', title: 'Delete ' + fotos[f].Title })
    .addClass("icon_delete")
    .appendTo(galleryidentifier)
    .click(function(){
        // Do something
    })

Upvotes: 16

Andrew Noyes
Andrew Noyes

Reputation: 5298

jQuery has a method called click, the argument to which is a callback function. In this example, I'm also going to use a (much) simpler shorthand for creating an image element:

$('<img/>').click(function () {
    // do something
}).attr({
    src: '/images/delete.gif',
    title: 'Delete ' + fotos[f].Title
}).addClass("icon_delete").appendTo(galleryidentifier);

Upvotes: 10

Boris Gu&#233;ry
Boris Gu&#233;ry

Reputation: 47585

you could just create a class when creating your image with addClass() method. And elsewhere have something like

$(document).ready(
  $("img.toBeClicked").click(function() {
    //some code
  };
};

Upvotes: 1

Paul Morie
Paul Morie

Reputation: 15778

You can add an event handler of this type using the click function in the same way you added the css class.

Upvotes: 1

Related Questions