views:

20

answers:

4

Hey guys,

I need to insert an image wherever the user clicks on a specified element (another image), and for it to sit in front of that image. Can this be done in javascript? If not, with what?

Thanks

A: 

You should post your html/structure too but you can go about something like this:

var el = document.getElementById('image_id');
var img = document.getElementById('image_id2');
var container = document.getElementById('container_id');

el.onclick = function(){
  container.appendChild(img);
};
Sarfraz
A: 

unless you're set on not using any external libraries, I would take a look at jQuery, which can make your life a whole lot easier for this kind of stuff

second
A: 

Sure, the basic flow would be to add an event listener to the onclick event. That event listener would then append the image to some container div.

The key point is the CSS for your images. Make sure that you're absolutely positioning your images and would be a good idea to use an incrementing z-index. You can capture the position values from the onclick event (for all the different values, see: http://www.quirksmode.org/js/events_properties.html#position). You would set these CSS values when you insert the image in javascript.

Nick Canzoneri
A: 

It should be possible. I personally use JQuery which makes these things pretty easy: http://jquery.com

This example should give you an idea of how you would accomplish this:

    <html>
    <head>
        <title>My Page></title>
        <style type="text/css">
            .overlay {
                position: absolute;
                z-index: 500;
            }
        </style>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
        <script type="text/javascript">
            $("#clickable-image").click(function() {
               var position = $(this).offset();
               $("#overlay-image").offset(position).show();
            });
        </script>
    </head>
    <body>
        <img id="clickable-image" src="path/to/image" />

        <div id="overlay-image" class="overlay" style="display: none;">
            <img src="path/to/overlay/image" />
        </div>
    </body>
</html>
Ross Peoples
doesnt seem to be inserting any image? :/ any ideas? Thanks
IceDragon