LukeSkyMc LukeSkyMc - 20 days ago 12
HTML Question

How to get variable id in $(variable).click, jquery

I have multiple images in a folder that I open directly on my page.
The problem is I want to get the id of these generated images, because each image has a specific style in css (height, width, margin-top etc). With this id I want to place them on my page on different area.

I want to get a variable id in $(variable).click, if it's possible.

From this line I generate images

$("#bgaff1").append("<img src='" + dir + filename + "' class='elm' id='"+item+"'>");


In out in the HTML code I have :

<img src="./img/catone/picture7.png" class="elm" id="picture7">


With this code I can only get the
class="elm"
, I don't know how to get the generated id by
item
variable

$('.elm').click(function(){
var pict1= document.getElementById("pict1");
pict1.src= dir + filename;
});


I already tried this :

$('.elm').click(function(){
var pict1= document.getElementById("pict1"); pict1.src= dir + filename;
var pict2= document.getElementById("pict2"); pict2.src= dir + filename;
});


But this code put the same style on the both images while they don't the same id. That's why I want to force the
$('.elm')
by the unique id of the pictures
#pict1
,
#pict2
... to handle each image with one different action.

Thank you for any help.

You can find the the ajax code here :

$(document).ready(function() {
$('.categorie').click(function() {
var dir = ($(this).attr('value'));
var fileextension = ".png";

$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function(data) {
//List all .png file names in the page
$('#bgaff1').empty();

$(data).find("a:contains(" + fileextension + ")").each(function() {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
var item = filename.replace('/', '').replace('.png', '');
$("#bgaff1").append("<img src='" + dir + filename + "' class='elm' id='" + item + "'>");
var filen = filename.replace(/[0-9]/g, "").replace('/', '').replace('.png', '');
$('.elm').click(function() {
var pict1 = document.getElementById("pict1");
pict1.src = dir + filename;

});
});
}
});
});
});

Answer

Instead of tring to find the generated id you can work with the class with this operation

$('.elm').click(function(){
  $(this).attr("src","_link_");
}); 

Above code will put the desired value to the clicked image.

Even still if you want find the current elements id, use following

$('.elm').click(function(){
  var id = $(this).attr("id");
});
Comments