Make images appear randomly in a div every few seconds... How? - javascript

Simple question, i have this DIV right, 400 * 250 px. And i have this image, fooi.png.
How can i make fooi.png randomly appear somewhere inside that div (and it doesn't remove the other images that already have been appeared) every 2 seconds?
Edit:
What i've got:
function placeimage(){
$('#div').append('<img src="fooi.png" alt="image" id="'. Math.floor(Math.random()*55) .'" onclick="doclick(this.id);">');
setTimeout(placeimage, 2000);
}
placeimage();

Write some css first
#div img {position: relative; float: left }
and javascript some how like this below
function placeimage(){
var t = $('<img src="fooi.png" alt="image" id="' + Math.floor(Math.random()*55) + '" onclick="doclick(this.id);">');
$('#div').append(t);
t.css('left', Math.floor(Math.random()*(400 - t.width())));
t.css('top', Math.floor(Math.random()*(250 - t.height())));
setTimeout(placeimage, 2000);
}
placeimage();

Use setInterval():
function placeimage(){
$div = $('#div');
$div.css('position','absolute');
id = 'ranimg'+Math.floor(Math.random()*55);
left = Math.floor(Math.random()*parseInt($div.innerWidth()));
top = Math.floor(Math.random()*parseInt($div.innerHeight()));
$div.append('<img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG" alt="image" id="'+id+'" onclick="doclick(this.id);" style="display: none; position: relative;">');
$img = $('#'+id);
$img.css('top',left+'px');
$img.css('left',top+'px');
$img.show();
setInterval(function(){placeimage();}, 15000);
}
placeimage();
http://jsfiddle.net/userdude/HfLZ4/

Related

how to change the src of an image when clicking and it return to the original after some time?

I have a page that displays several hidden divs when clicking on image-buttons (next and previous). sometimes takes a few seconds for its content to show up correctly, so I had the idea of ​​delaying the functions a bit to "give time" for the content to "prepare". While that time the image exchanges for a gif.
I already started and saw that it works, I got a simple way with tris.src to change the img and setInterval for the delay, direct on my onclick="", but I need the original image to automatically return to the original after 2 or 3 seconds because it can showed again (when clicked on previous button) and should not to be a gif anymore! and don't know how to do this. can you help me?
CSS:
div1, #div2 {width: 100px; height: 100px; background: yellow;position: relative;
next {position: absolute bottom: 20px; left: 20px}
}
HTML & JS:
<div id="div1">
content1
<img src="next.png" id="next" onclick="setTimeout(replace, 1000); this.src='prev.png'">
<input type="hidden" value="prev.png" id="hdnPreviousPng" />
</div>
<div id="div2" style="display: none">content2
<img src="next.png" id="next" onclick="setTimeout(replace2, 1000); this.src='prev.png'">
<input type="hidden" value="prev.png" id="hdnPreviousPng" />
</div>
<script>
function replace() {
document.getElementById("div1").style.display="none";
document.getElementById("div2").style.display="block";
setInterval(function(){
let originalSrc = $('#hdnPreviousPng').val();
$('#next').attr('src', originalSrc);
}, 3000);
}
function replace2() {
document.getElementById("div2").style.display="none";
document.getElementById("div1").style.display="block";
setInterval(function(){
let originalSrc = $('#hdnPreviousPng').val();
$('#next').attr('src', originalSrc);
}, 3000);
}
</script>
You could just use a simple data attribute to store some state and swap in and out image source tags.
Here is an example of how this would work using JavaScript:
function clicked() {
replace();
setTimeout(replace, 1000);
}
function replace() {
var next = document.getElementById("next").getAttribute("data-img-src");
var current = document.getElementById("next").src;
document.getElementById("next").setAttribute("data-img-src", current);
document.getElementById("next").src = next;
}
<div id="div1">
<img id="next" src="http://via.placeholder.com/100?text=first" data-img-src="http://via.placeholder.com/100?text=second" onclick="clicked();">
</div>
If you need to account for multiple clicks and still return to the original image you will need some more state and can try this:
function clicked() {
replace();
setTimeout(replaceOriginal, 1000);
}
function replace() {
var next = document.getElementById("next").getAttribute("data-img-src");
document.getElementById("next").src = next;
}
function replaceOriginal(){
var original = document.getElementById("next").getAttribute("data-img-original");
document.getElementById("next").src = original;
}
<div id="div1">
<img id="next" src="http://via.placeholder.com/100?text=first" data-img-original="http://via.placeholder.com/100?text=first" data-img-src="http://via.placeholder.com/100?text=second" onclick="clicked();">
</div>

jQuery FadeIn and FadeOut animation show white color inbetween

I have change the background image of div every 5 seconds to make it look nices i am adding image to div as background. My script adds white color in between image transition which make it look bad, i tried to fix it but not much seems to work. Below code snippet now shows image using FadeIn effect if i add FadeOut to this then it addes white between transition.
var imgSrcs = [
"../img/bg1.jpg",
"../img/bg2.jpg",
"../img/bg3.jpg",
"../img/bg4.jpg",
"../img/bg5.jpg"
];
var index = 1;
$('.intro').css("background-image", "url(" + imgSrcs[0] + ")")
$('.intro').fadeIn('slow', animateBackground());
function animateBackground() {
window.setTimeout(function () {
var url = imgSrcs[index];
index++;
if (index == 5)
index = 0;
$('.intro').delay(5000).fadeIn(1000, function () {
$(this).css("background-image", "url(" + url + ")")
}).fadeIn(1000, animateBackground())
});
}
I am not sure how to fix this so it will work image FadeOut & FadeIn between images
Fiddle http://jsfiddle.net/7xxx6ah3/5/
use this
<script type="text/javascript">
$('#background_cycler').hide();//hide the background while the images load, ready to fade in later
</script>
<img class="active" src="images/img1.jpg" alt=""/>
<img src="images/img2.jpg" alt="" />
<img src="images/img3.jpg" alt="" />
<img src="images/img4.jpg" alt=""/>
<img src="images/img5.jpg" alt="" />
</div>
<style>
#background_cycler{padding:0;margin:0;width:100%;position:absolute;top:0;left:0;z-index:-1}
#background_cycler img{position:absolute;left:0;top:0;width:100%;z-index:1}
#background_cycler img.active{z-index:3}
</style>
<script>
function cycleImages() {
var $active = $('#background_cycler .active');
var $next = ($('#background_cycler .active').next().length > 0) ? $('#background_cycler .active').next() : $('#background_cycler img:first');
$next.css('z-index', 2);//move the next image up the pile
$active.fadeOut(1500, function () {//fade out the top image
$active.css('z-index', 1).show().removeClass('active');//reset the z-index and unhide the image
$next.css('z-index', 3).addClass('active');//make the next image the top one
});
}
$(window).load(function () {
$('#background_cycler').fadeIn(1500);//fade the background back in once all the images are loaded
// run every 7s
setInterval('cycleImages()', 7000);
})
</script>

Background Image Rotator with jQuery?

I am working on a website that the background image will fade from one to another, I have it setup and working about 98%. There is just one little problem. When it first loads and does it's first fade it fades to white and then to the image, instead of fading straight into the next image. After that it work beautifully. This is using jQuery 1.9 and I have jQuery noConflict on since the previous developer coded the sites menu using MooTools.
<html>
<head>
<script src="js/jquery.js">
</script>
<script>
var $s = jQuery.noConflict();
function swapImages(){
var $sactive = $s('#myGallery .active');
var $snext = ($s('#myGallery .active').next().length > 0) ? $s('#myGallery .active').next() : $s('#myGallery img:first');
$snext.fadeIn(1500).addClass('active');
$sactive.fadeOut(2000, function(){
});
$sactive.removeClass('active');
};
$s(document).ready(function(){
// Run our swapImages() function every 5secs
setInterval('swapImages()', 5000);
});
</script>
</head>
<style>
#myGallery{
position:relative;
width:100%; /* Set your image width */
height:auto; /* Set your image height */
}
#myGallery img{
display:none;
position:absolute;
top:0;
width: 100%;
left:0;
}
#myGallery img.active{
display:block;
}
.home-page-rotator{
position:absolute;
width:100%;
z-index:-10;
}
</style>
<body>
<div class="home-page-rotator" id="myGallery">
<img src="images/1.jpg" class="active" />
<img src="images/2.jpg" />
<img src="images/3.jpg" />
</div>
</body>
</html>
I took out all the content so you can test if you wanted but the is everything that runs the background rotation and fade. Also I have the CSS in a seperate file but for posting to here I just put it inline so you can see the CSS behind the code. Let me know what I should do to fix this?
Moving the remove class method to the function call of the fadeout seems to work better for me (at least in Chrome):
<script>
var $s = jQuery.noConflict();
function swapImages(){
var $sactive = $s('#myGallery .active');
var $snext = ($s('#myGallery .active').next().length > 0) ? $s('#myGallery .active').next() : $s('#myGallery img:first');
$sactive.fadeOut(2000, function(){
$sactive.removeClass('active');
});
$snext.fadeIn(1500).addClass('active');
};
$s(document).ready(function(){
// Run our swapImages() function every 5secs
setInterval('swapImages()', 5000);
});
</script>
I ran into this problem a while back and I found the easiest solution was to switch from img elements to using two divs and the background-image css url to display your images. I made a simple slider for that a while back. You're welcome to copy whatever you need from it.
Background slider source
In essence, if you have two divs that are absolutely positioned as the background elements, you can cycle their z-indexes and fade them in and out. Furthermore, you can load the next image in a constructed img element and once it has loaded, change the background-image of the hidden div and fade to it. This means that there is no loading shown and you can fade directly into the slideshow.
Here's some pseudo code below, but it would probably be easier to just look at the real functions in the source.
base.next_slide = function () {
"current slide" = "next slide";
base.containers[the_shown_container].fadeOut(duration,function () {
$(this).css({'background-image':'url("' + "Next image url" + '")',
"z-index":"-2"});
base.containers[the_next_container].css("z-index","-1");
$(this).show();
the_shown_container = the_next_container;
});
};
Plugin.prototype.init = function (base) {
$('<img/>').attr('src', "Next image url").load(function() {
base.containers[the_next_container].css('background-image', 'url(' + "Next image url" + ')');
if ("there's only one image in the slider"){
base.containers[the_shown_container].fadeOut(duration,function () {
$(this).css("z-index","-2");
base.containers[the_next_container].css("z-index","-1");
});
return;
}
base.next_slide();
setInterval(base.next_slide ,base.o.interval);
});
};

jQuery simple slideshow creates long pauses

Here is this simple slideshow I'm using:
function slideShow(){
var current = $('#animation .show');
var next = current.next().length ? current.next() : current.parent().children(':first');
current.removeClass('show');
next.addClass('show');
setTimeout(slideShow, 500);
}
$(document).ready(function() {
slideShow();
});
It works but it creates long pauses between images...Is there a way to fix this?
Thanks in advance!
EDIT
this is the HTML code,I guess pauses was the wrong word, what I want to achieve is every image is displayed immediately after the other, right now I have a small gap that nothing is displayed.
<div id="animation">
<img alt="graphic" class="show" src="files/animation_img/GRAPHIC.jpg" />
<img alt="design" src="files/animation_img/DESIGN.jpg" />
<img alt="etc" src="files/animation_img/ETC.jpg" />
</div>
and the CSS:
#animation img
{
position:fixed;
top:400px;
left:700px;
display:none;
visibility:hidden;
width:200px;
height:100px;
}
Try this
function slideShow(){
var current = $('#animation .show');
var next = current.next().length ? current.next() : current.parent().children(':first');
current.removeClass('show');
next.addClass('show');
}
$(document).ready(function() {
setInterval(slideShow, 500)
});

How to add fading or image transition effect using JQuery?

I have just one <img> element on my page. I change the src attribute of this image every 7 seconds.
I see the new images every 7 secs, but it would be nicer if I can add some fading or transitions effect when loading new image.
Does some have simple script for this?
I don't need any plugin. Just need some clue or few lines of sample for doing it.
Despite what KaiQing mentioned, you can use the callbacks ability of jQuery to fade in/out the image while you're changing it. This can be done like so: http://www.jsfiddle.net/bradchristie/HsKpq/1/
$('img').fadeOut('slow',function(){
$(this).attr('src','/path/to/new_image.png').fadeIn('slow');
});
You'll want to use two images:
<img id="backImg" />
<img id="frontImg" />
Set #backImg to be behind #frontImg like so:
#backImg
{
position: absolute;
}
Then, in your code that fires every 7 seconds, fadeOut the front image... this will automatically do your crossfade effect because the back image is already loaded behind it. When the fade is done, set the source of the front image to the back image's src, show it, and pre-load the next image into the back image:
function transitionImages(preloadImgUrl)
{
$("#frontImg").fadeOut("slow", function()
{
$("#frontImg").attr("src", $("#backImg").attr("src")).show();
$("#backImg").attr("src", preloadImgUrl);
}
}
This all assumes your images are identically sized. If not, you'll want to be just a little more elaborate with the css and wrap the images in divs that fade out.
You can't do this with just one image.
Check this out:
<div id="main_over"></div>
<div id="main_img"></div>
<div id="himg" style="display:none; clear:both; margin-top:40px;">
<img id="si_15" src="http://website.com/media/uploaded/home_slideshow/53/dummy_image_large_1__large.jpg" alt="dummy_image_large_1" />
<img id="si_16" src="http://website.com/media/uploaded/home_slideshow/53/dummy_image_large_2__large.jpg" alt="dummy_image_large_2" />
<img id="si_17" src="http://website.com/media/uploaded/home_slideshow/53/dummy_image_large_3__large.jpg" alt="dummy_image_large_3" />
<img id="si_18" src="http://website.com/media/uploaded/home_slideshow/53/dummy_image_large_4__large.jpg" alt="dummy_image_large_4" />
</div>
<style>
#main_over{position:absolute; z-index:10; width:800px; height:600px; background:#fff; display:block;}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var i = 0;
$('#himg img').each(function(){
if(i == 0)
{
$('#main_over').html('<img src="' + $(this).attr('src') + '" alt="" />');
}
if(i == 1)
{
$('#main_img').html('<img src="' + $(this).attr('src') + '" alt="" />');
}
i ++;
slide.arr.push($(this).attr('src'));
});
setTimeout(function(){
if(slide.arr.length < 2)
slide.fade(0);
else
slide.fade(2);
}, 3000);
});
var slide = {
arr: Array(),
fade: function(i)
{
$('#main_over').fadeOut("medium");
setTimeout(function(){slide.next(i);}, 1000);
},
next: function(i)
{
$('#main_over').html($('#main_img').html());
$('#main_over').css('display', 'block');
$('#main_img').html('<img src="' + slide.arr[i] + '" alt="" />');
i++;
if(i >= slide.arr.length)
i = 0;
setTimeout(function(){slide.fade(i);}, 3000);
}
}
</script>

Categories