Reputation: 1
I'm creating a bunch of div
s and inserting thumbnail images through a referenced js
file using a simple function. Basically i'm trying to assign the click handler to each new div
in the loop but for probably syntax reasons it isn't working.
This is my code ( updated )...
function makethumbs() {
for (var i = 0; i < 14; i++) {
var backgroundUrl = script_vars + "/images/gallery/thumbs/g" + (i+1) + ".jpg",
newdiv = $('<div />', {id: 'thumbnail'+i, width: 145, height: 84});
newdiv.css({display:'inline',
float:'left',
margin:'2px 2px 0 0',
color:'#000',
fontSize:'18px',
zIndex:0,
html:'P',
background: 'url(' + backgroundUrl + ')'
});
newdiv.click(function() {
$(this).stop(true, true).fadeTo('slow', 0);
});
$('#thumbholder').append(newdiv);
}
$('#arrowright').click(function() {
var L = $('#thumbholder'),
margL = parseInt(L.css('marginLeft'), 10),
newMarg = (margL - 147) + 'px',
anim = {opacity: 1};
anim["marginLeft"] = newMarg;
$('#thumbholder').stop(true, true).animate(anim, 400);
});
}
Theres an extra click handler there too for #arrowright
which works fine. Not sure if its a z ordering thing as the clickable arrow div
is inside a container which overlays the thumbnail div
s if that makes sense.
Upvotes: 0
Views: 407
Reputation: 318182
Why not keep on using jQuery ?
function makethumbs() {
for (var i = 0; i < 14; i++) {
var backgroundUrl = script_vars + "/images/gallery/thumbs/g" + (i+1) + ".jpg",
newdiv = $('<div />', {id: 'thumbnail'+i, width: 145, height: 84});
newdiv.css({display:'inline',
float:'left',
margin:'2px 2px 0 0',
color:'#000',
fontSize:'18px',
zIndex:0,
html:'P',
background: 'url(' + backgroundUrl + ')'
});
newdiv.click(function() {
$(this).stop(true, true).fadeTo('slow', 0);
});
$('#thumbholder').append(newdiv);
}
$('#arrowright').click(function() {
var L = $('#thumbholder'),
margL = parseInt(L.css('marginLeft'), 10),
newMarg = (margL - 147) + 'px',
anim = {opacity: 1};
anim["marginLeft"] = newMarg;
$('#thumbholder').stop(true, true).animate(anim, 400);
});
}
as your main problem is trying to attach a click handler with jQuery syntax to a native JS DOM element.
Upvotes: 2
Reputation: 1420
change newDiv.click
to $(newDiv).click
since you seem to be using jQuery; however if you want to continue using native javascript you can set an event for the element like so:
newDiv.addEventListener('click',function(){
//you code here
});
Upvotes: 0