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?
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With