Phill Healey
Phill Healey

Reputation: 3180

Add value to dynamically generated image then display on click

I'm creating a dynamic image grid. I need to create the functionality that will allow a user to click an image and for that image to be shown in a preview box elsewhere on the page. Alongside this should be a short description which is also grabbed from an attribute of the image clicked.

Here is some static code representing what I already have:

<div class="indent-left-10 sliderBlock">
    <div class="image-feed-slider">
        <img src='youtube-300x124.jpg' alt='Creating a YouTube presence' class='clickable'>
        <img src='youtube-300x1240.jpg' alt='Creating a plastic presence' class='clickable'>
        <img src='youtube-300x1247.jpg' alt='Creating a wrapping presence' class='clickable'>

And my JQuery:

$('.clickable').click(function() {
    alert('TEST ALERT');
});

At the moment this code simply fires the alert as a test to function. What I need to establish now is:

  1. How to add the extra info to the image(s). Can I just use pseudo attribute?
  2. How can I grab this data via JQ/jQuery from the link

Once I've got the info, I know how to insert it into a div elsewhere on the page.

Upvotes: 2

Views: 229

Answers (2)

Enrique Carro
Enrique Carro

Reputation: 380

First of all, since your grid is beeing created dynamicly, you should use .on() instead of .click().

$('.image-feed-slider').on("click", ".clickable", function() {
     // display image
});

You can prefix attributes with data:

<img data-description="image description" src='youtube-300x124.jpg' alt='Creating a YouTube presence' class='clickable' >

Then you can use jquery's data method to get the description:

$('.image-feed-slider').on("click", ".clickable", function() {
     var description = $(this).data("description");
     // display image
});

Upvotes: 2

ZiNNED
ZiNNED

Reputation: 2650

Unless I've misunderstood the question, I would use data--attributes to store the description in the img-element. Then it's a simple matter of reading these attributes with jQuery. Something like this:

1) HMTL

<img src='youtube-300x124.jpg' alt='Creating a YouTube presence' data-desc='A description about creating a YouTube presence' class='clickable'>
<img src='youtube-300x1240.jpg' alt='Creating a plastic presence' data-desc='A description about creating a plastic presence' class='clickable'>
<img src='youtube-300x1247.jpg' alt='Creating a wrapping presence' data-desc='A description about creating a wrapping presence' class='clickable'>

2) jQuery

$('.clickable').click(function() {
    alert($(this).data('desc'));
});

Upvotes: 3

Related Questions