Reputation: 2201
I'm trying to add inner shadow to userphotos (img) in the page. It works fine unless a userphoto element is added dynamically or moved from its position. Is there anyway to calculate the position live or recalculate position when elements is moved.
jQuery('.UserPhoto').each(function(){
var photo = jQuery(this);
var photowidth = photo.width();
var photoheight = photo.height();
var photoposition = photo.position();
var shadowcss = {
'position' : 'absolute',
'top' : photoposition.top + 'px',
'left' : photoposition.left + 'px',
'height' : photoheight + 'px',
'width' : photowidth + 'px'
}
jQuery(this).after("<div class='userPhotoShadow'></div>");
jQuery(this).next().css(shadowcss);
});
Upvotes: 0
Views: 320
Reputation: 876
First off, I think it's very inefficient to append a shadow element and have to deal with its position whenever the photo is being moved.
Another approach (way better imo) would be to wrap an element around your photos and then append your shadow in there, like this:
$('.UserPhoto').each(function () {
$(this).wrap('<div class="UserPhotoWrapper" />')
.parent()
.append('<div class="UserPhotoShadow" />');
});
And here is a fiddle to show you more what I'm talking about. Hope that helps!
Upvotes: 1
Reputation: 10211
First part is simple. Hook up to move/resize events and update your shadow element there.
Second part can be tricky. There are DOMSubtreeModified/DOMNodeInserted/etc. events but they are not well supported by various browsers. It is much easier to simply call you shadow creation code manually after you create a new photo.
The last part is how do you figure if the photo already has a shadow. Ideally you wouldn't have to, but if you add photos in bulk and don't really have selection of the new photos ready, then your code above can simply add a marker class has-shadow
to the photos that it already processed and ignore those that already have it.
Alternatively to working with move/resize events you could simply add your shadow div inside the photo div (ass opposed to after it). As long as you don't set overflow:hidden
it will just work with basic CSS and without any javascript involved.
You could also try to use CSS pseudo elements :before
and :after
instead of adding an element via javascript. Depending on what exactly your shadow looks like, that may or may not work, but it is much cleaner and much more performant than trying to do it via javascript.
Upvotes: 0