+40 745 232 788

Online Solutions Development Blog   |  

RSS

Place element over another in javascript

posted by ,
Categories: JavaScript
Taggs , ,

If you want to place an html element over another one using javascript for some reason here you will find the solution. Why you might want to do this? Maybe you want to place an “online now” stamp on the corner of the user avatar or an “on sale” stamp on some of the products on your online store.

This will be something like an watermark but without editing the image. This has two main characteristics: it can be dynamically updated (like the online status of an user or the promotions on your store) but it is not the solution for protecting your pictures.

Since there are a lot of watermark solutions out there I will focus only on this other matter.

So what’s the first thing we need? The absolute position of the element you want to apply the stamp on.

Getting the absolute position of an element using JavaScript

You can do this using this function:

function getXYpos(elem)
{
   if (!elem)
   {
      return {"x":0,"y":0};
   }
   var xy={"x":elem.offsetLeft,"y":elem.offsetTop}
   var par=getXYpos(elem.offsetParent);
   for (var key in par)
   {
      xy[key]+=par[key];
   }
   return xy;
}

This function goes from the element you provide through all of its parents and finds out the absolute position by adding the relative positions.

Now we need the final function: the one that places the stamp.

Add element over another using JavaScript

This is a pretty simple function but it also has comments for almost every line.

		function setStamp()
		{
			// create a new element.. the one that we will place on top
			var new_el = document.createElement('img');
			// set the source for the image element
			new_el.setAttribute('src', 'online.png');
			// add an id to the element so we could find it later
			new_el.setAttribute('id', 'photoStamp');
			// set absolute position to the new element
			new_el.style.position = 'absolute';
			// this is the picture we need to set the stamp on
			var main_pic = document.getElementById('userAvatar');
			// get the coordinates for this "parent"
			var big_coordinates=getXYpos(main_pic);
			var bp_x = big_coordinates['x'];
			var bp_y = big_coordinates['y'];
			// set these values for the new created element
			new_el.style.left =  bp_x + 'px';
			new_el.style.top = bp_y + 'px';
			// get the container for the picture
			var container = document.getElementById('userAvatarContainer');
			// add the new element as child for the container
			container.appendChild(new_el);
		}

That’s all. But there are some improvements we can add.

What happens if the window is resized? The new element (that has an absolute position) will no longer be on top of its parent. What do we need to do? Call this function again so the absolute coordinates will be the new ones. How? Like this:

window.onresize=setStamp;

But the “old” stamp will still be there. So we need to update our function so that every time we call it it would check if the stamp exists and remove it. There is no direct way to remove an element using javascript but there is a way to remove the child of an element. So we will add something like this:

elm.parentNode.removeChild(elm);

So now we are ok, this function can be called by another one (ajax based) that checks the user/product status at a timed interval or any other way you want.

What are the useful things this small script takes advantage of:

  • getting the absolute position of an element
  • removing an element
  • creating a new element
  • assigning absolute positions to an element.

All these using js.

As I got used after getting a nice feedback from one of the readers I will give you a download link for the full working example: this is it 🙂

If you have any ideas or questions please feel free to post them as a comment to this post using the form below.

If you liked this post
you can buy me a beer

4 Responses to Place element over another in javascript

  1. Thanks, very useful !!!!!!!!!!

  2. thank you man! very good work.

  3. What about getBoundingClientRect?

    • What about it? Since you are just dropping a name without any details I will try to guess: yes, it is a method you could use to get the position for the element you want to place the stamp on.

      Yes, it is a pretty good idea, and you could use it if you want, especially if you don’t forget that it doesn’t include the document scroll offset. You could also use jQuery’s offset method if you already have the library included in your project. And I am sure that there are other ways also.

      The purpose of this short blog post is not to show all the ways you could to this, but one of them. To keep it short and to the point the article just outlines a few thing. I am sure that are parts that you could improve, things like the functions now defined in global scope, the way the event is attached, the way the element is removed, the way you get the coordinates an (maybe) others.

      So the blog post, and (our) blog posts in general, shows the idea and it is up to everyone how the it is implemented. If you want to use getBoundingClientRect feel free to do it and we also welcome your feedback here after that.

Add a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Also, if you want to display source code you can enclose it between [html] and [/html], [js] and [/js], [php] and [/php] etc