Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a DIV next to the cursor position on click

What I'm trying to do is, when a user clicks somewhere on a page, a div containing a random image would show up on in the position of a click and it stays there. This must be able to be repeated, showing a different image every time. Any suggestions?

like image 801
George Ciobanu Avatar asked Dec 25 '12 17:12

George Ciobanu


2 Answers

Here's a working fiddle.

JS:

$(function(){
    var fadeDelay = 1000;
    var fadeDuration = 1000;
    $(document).click(function(e){
        var div = $('<div class="image-wrapper">')
            .css({
                "left": e.pageX + 'px',
                "top": e.pageY + 'px'
            })
            .append($('<img src="" alt="myimage" />'))
            .appendTo(document.body);

        setTimeout(function() {
            div.addClass('fade-out');           
            setTimeout(function() { div.remove(); }, fadeDuration);
        }, fadeDelay);
    });
});

CSS:

body {
    position: relative;
}

.image-wrapper {
    position: absolute;
    transform: translate(-50%, -50%);
    opacity: 1;
}

.image-wrapper.fade-out {
    opacity: 0;
    transition: opacity 1s ease-in-out;
}
like image 68
Paul Fleming Avatar answered Nov 13 '22 12:11

Paul Fleming


With random images from 1 to 10:

jQuery(document).ready(function(){
  $(document).click(function(e){
    var num = Math.floor((Math.random()*10)+1);
    var img = $('<div>Image '+num+':<img src="image' + num + '.png" /></div>');
    $("#img_container").html(img).offset({ top: e.pageY, left: e.pageX});
  });
})

DEMO

like image 40
user1517081 Avatar answered Nov 13 '22 12:11

user1517081