Change image every 10 second - javascript

I want to change image every 10 seconds in javascript, can someone help me?
Here's the images, I only want add some code on javascript without changing these code below
HTML
<body onload = "imageChanger()">
<div>
<ul>
<li><img src = "images/img1.jpg"/></li>
<li><img src = "images/img2.jpg"/></li>
<li><img src = "images/img3.jpg"/></li>
<li><img src = "images/img4.jpg"/></li>
</ul>
</div>
</body>
CSS
div {margin: 50px auto; height: 500px; width: 800px; overflow: hidden; border: 10px solid;}
img {width: 800px; height: 500px;}
ul {list-style-type: none; padding: 0; margin: 0;}
I want to add some code that will change image on load:
JS
function imageChanger()
{
//Code here
}

Here is what I did for a similar scenario.
<body id="background">
<script>
$(function () {
var imageArray = ['BG-1.jpg', 'BG-2.jpg', 'BG-3.jpg', 'BG-4.jpg', 'BG-5.jpg', 'BG-6.jpg', 'BG-7.jpg', 'BG-8.jpg', 'BG-9.jpg', 'BG-10.jpg', 'BG-11.jpg', 'BG-12.jpg', 'BG-13.jpg', 'BG-14.jpg', 'BG-15.jpg', 'BG-16.jpg', 'BG-17.jpg', 'BG-18.jpg', 'BG-19.jpg', 'BG-20.jpg', 'BG-21.jpg', 'BG-22.jpg']
// on page load
$('#background').css({ 'background-image': 'url(/Content/img/BackGround/' + imageArray[Math.floor(Math.random() * imageArray.length)] + ')', 'background-size': 'cover' })
// every 10 seconds change to random image name in the array
setInterval(function () {
$('#background').css({ 'background-image': 'url(/Content/img/BackGround/' + imageArray[Math.floor(Math.random() * imageArray.length)] + ')', 'background-size': 'cover' })
}, 10000);
});
</script>
</body>

You can use setInterval() for this.
Code
var i = 0;
setInterval(changeImage, 10000);
changeImage(); //Initial call to hide the images on start
function changeImage() {
i = (i + 1) % $('li').length; //Make sure the list wraps back to 0
$('li:eq(' + i + ')').show().siblings().hide();
}
Fiddle

Related

Add different images when mouse moving in jquery

I'm trying to make a jquery code where you can show different images (1-3 different images) when you move the mouse around.
The images will be right beside the cursor, and they will only appear 1-3, not more than that. And each time the mouse moves, these images will change.
I currently have this as my html code,
<div class="mainbody">
<section class="container">
<div class="img_div">
</div>
</section>
</div>
And my jquery code looks like this:
let img_array = ['./img/awards_icon.png', './img/norinuri_icon.png'];
$("div.mainbody").mousemove(function(e) {
for(i=0; i<img_array.length; i++){
$('.img_div').append("<img src='" + img_array[i] +"'/>");
$('.img_div').fadeIn("5000");
$('.img_div').finish().fadeOut("5000");
$('.img_div').offset({
left: e.pageX,
top: e.pageY + 20
});
}
});
The 2 images that I have in my jquery array appears when the mouse moves, but instead of only having 2 images these images add continuously, without stopping.
So each time I would move my mouse, the images would continue to add infinitely.
I will add more images in the jquery array for sure,
but how should I have only two images added, and change these images as I move the mouse?
Use background-image
var imageArr=["https://www.w3schools.com/css/paper.gif","https://www.w3schools.com/css/gradient_bg.png","https://www.w3schools.com/css/img_tree.png"];
var count=0;
$( ".mainbody" ).mouseover(function() {
$( ".img_div" ).css('background-image', 'url("' + imageArr[count] + '")');
if(count == imageArr.length-1)
count=0;
else
count++;
});
.mainbody{
width: 500px;
height: 500px;
border:1px solid red;
}
.img_div{
width: 200px;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mainbody">
<section class="container">
<div class="img_div">
</div>
</section>
</div>
Here is working fiddle;
USING mousemove (to avoid the images to change so many times while mouse move I use timeout)
var imageArr=["https://www.w3schools.com/css/paper.gif","https://www.w3schools.com/css/gradient_bg.png","https://www.w3schools.com/css/img_tree.png"];
var count=0;
var timeoutid = 0;
function setImage() {
$( ".img_div" ).css('background-image', 'url("' + imageArr[count] + '")');
if(count == imageArr.length-1)
count=0;
else
count++;
}
$(".mainbody").mousemove(function() {
clearTimeout(timeoutid);
timeoutid = setTimeout(setImage, 100);
});
.mainbody{
width: 500px;
height: 500px;
border:1px solid red;
}
.img_div{
width: 200px;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="mainbody">
<section class="container">
<div class="img_div">
</div>
</section>
</div>
화이팅!
I have created a working example for you. You can try it now:
<div class="mainbody">
<section class="container">
<div class="img_div">
hello
</div>
</section>
css
.mainbody {
border:1px solid red;
display:block;
height:1000px
}
jquery
let img_array = ['https://anotherjavaduke.files.wordpress.com/2018/08/avataaars-2.png',
'https://images2.minutemediacdn.com/image/upload/c_crop,h_1192,w_2121,x_0,y_111/f_auto,q_auto,w_1100/v1554921884/shape/mentalfloss/22461-istock-176984635.jpg'];
$("div.mainbody").on('mousemove', function(e) {
var i;
$('.img_div').html('')
for (i = 0; i < img_array.length; i++) {
console.log($('.img_div').has('img').length)
if ($('.img_div').has('img').length < img_array.length) {
$('.img_div').append("<img style='width:100px; height:100px' src='" + img_array[i] + "'/>");
$('.img_div').fadeIn("5000");
$('.img_div').finish().fadeOut("5000");
$('.img_div').offset({
left: e.pageX,
top: e.pageY + 20
});
}
}
});
Working example
[Codepen] https://codepen.io/prashen/pen/ZEEqJEo

element height() not adding + 200?

I would like to scroll to the end of the container. The element is having new items added via ajax on click, so I am recalculating its height each time I click to load more. The page scrolls fine but I would like to also add the navigation height in order to have the exact pixels. It looks like it is not adding + 224 tho
Html
lorem
New items are added via a click and ajax.
Css
nav {
height: 90px;
}
#container {
margin-top: 104px;
margin-bottom: 120px;
}
Jquery
var page = $("html, body");
var pos = $("#container").height() + 224;
page.animate({scrollTop: pos}, 1000);
I think you want something like this no ?
var page = $("html, body");
console.log($("#t").height());
var pos = $("#t").height() - 500;
console.log(pos);
page.animate({scrollTop: pos}, 1000);
div{
height: 1000px;
width: 50px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="t"></div>
you can use scrollIntoView for last added item
var j=0;
function Add(){
var item=null;
for(var i=0;i<20;i++){
j++
item= $('<div class="item">'+j+'</div>').appendTo("#container")
}
item[0].scrollIntoView()
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" onclick="Add()" Value="Add" />
<div id="container"></div>

Custom JQuery Slider (auto-slide)

I'm trying to make image slider with my own without using plugins.
1st question : How to make the animation horizontally
2nd question : Whatever the size of the image, it must cover the height and width of its container, but keeping the proportionalities original image. The image can be rendered partially. How to make this?
3rd question : About the code of the slide, if anyone finds any improvement to make it lighter and more elegant, would be welcome.
$(function(){
setInterval(function(){
var displayed = $(".img-header.displayed");
displayed.animate({opacity : 0}, 500, function() {
displayed.css("display","none");
displayed.addClass("not-displayed").removeClass("displayed");
if(displayed.next(".img-header.not-displayed").length == 0){
$(".img-header:first").css("display","inline-block").css("opacity","1");
$(".img-header:first").addClass("displayed").removeClass("not-displayed");
$(".img-header:first").animate({opacity : 1}, 500);
}
else{
displayed.next(".img-header.not-displayed").css("display","inline-block").css("opacity","1");
displayed.next(".img-header.not-displayed").addClass("displayed").removeClass("not-displayed");
displayed.next(".img-header.not-displayed").animate({opacity : 1}, 500);
}
});
}, 4000);
});
#slider-container{height: 200px; width: 200px;}
#slider-container img.img-header{ width: 100%; height: auto;}
.displayed{display: inline-block;}
.not-displayed{display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider-container">
<img class="img-header displayed" src="http://i.stack.imgur.com/AIHnl.png" />
<img class="img-header not-displayed" src="http://i.stack.imgur.com/XQrms.png" />
</div>
I think you might be looking for something like this.
The slider here is position:relative; with top:100px; you can set as per your requirement. Still i suggest you to keep it positioned relative.
Slider has width:700px and height:500px;, you can change as per your requirement, it will be fine for whatever aspect ratio of image you have or all images with different aspect ratio.
There is an array for images to load which are serially numbered in one location, so you may give little more understanding into that. I have made a comment for that in JS file
Also you could change slider speed and delay as per your requirements.
When you hover over image it will pause the slider, which resumes after you leave image.
Snippet :
$(document).ready(function(){
var noPannel = document.getElementsByClassName("pannel").length;
var i;
var imgArr = [ ];
var pannelWidth = $(".slider_holder").width();
var totalWidth = noPannel*pannelWidth;
for (i=1;i<=noPannel;i++)
{
imgArr[i] = "http://www.picget.net/background/" + i + ".jpg"; //if you have somewhere on other path
//imgArr[i] = " " + i + ".jpg"; //use this if you have image in same folder/path.
}
for(i=1;i<=noPannel;i++)
{
$(".pannel:nth-child("+i+")").css("background","url("+imgArr[i]+")");
}
function jsslider()
{
var curScroll = $(".slider").scrollLeft();
var endScroll = totalWidth - (pannelWidth*2);
if(curScroll<=endScroll)
{
$(".slider").animate({scrollLeft: '+=' + pannelWidth +'px'},900,"swing");// Replace 900 for speed
}
else
{
$(".slider").animate({scrollLeft: '0px'},500,"swing"); // Replace 500 for speed to go bck to first
}
}
var interval = setInterval(jsslider, 3000); // Replace 3000 for delay between each slide.
$(".pannel").hover(function () {
clearInterval(interval);
}, function () {
interval = setInterval(jsslider, 3000); // Replace 3000 for delay between each slide.
});
}); // document.ready ENDS
html, body, *
{
margin:0px;
width:100%;
height:100%;
}
.slider_holder
{
margin-left:auto;
margin-right:auto;
display:block;
position:relative;
top:100px;
width:1024px;
height:768px;
background:#eee;
overflow:hidden;
}
.slider
{
width:auto;
height:100%;
width:100%;
white-space: nowrap;
overflow:hidden;
}
.pannel
{
margin:0px;
display:inline-block;
width:100%;
height:calc(100% - 1px);
/*border:1px solid red;*/
background-size:cover !important;
background-repeat:no-repeat;
background-position:50% 50% !important;
position:relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="sliderFunc()">
<div class="slider_holder">
<div class="slider">
<span class="pannel"> </span>
<span class="pannel"> </span>
<span class="pannel"> </span>
<span class="pannel"> </span>
<span class="pannel"> </span>
</div>
</div>
</body>

Improve slide effect

I have created a simple slider
html
<div id="sldvid1" class="slider" >
<img picnum="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png" />
<img picnum="2" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png" />
<img picnum="3" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png" />
</div>
<hr>
<div id="sldvid2" class="slider" >
<img picnum="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png" />
<img picnum="2" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png" />
<img picnum="3" style="display:none;" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png" />
</div>
$
var timer1 = setInterval(runSlide, 1000);
var curnum = 1;
function runSlide()
{
curnum = $(".slider img:visible").attr('picnum');
//$("#sldvid1 img[picnum=" + curnum + "]").fadeOut();
if(curnum == 3){
curnum = 1;
}
else
{
curnum++;
}
// $(".slider img").hide();
//$(".slider img[picnum=" + curnum + "]").show();
$(".slider img").hide();
$(".slider img[picnum=" + curnum + "]").show();
//console.log(curnum);
}
CSS
.slider{
height:50px;
}
Demo
http://jsfiddle.net/mparvez1986/vf401e2y/
Everything is working fine, I just need some one to improve effect so that it could effect like moving from left to right, I tried with some effect, but it seems it required some css manipulation as well
Thanks
I modified your code to create a carousel where images are slid in and out. I accomplished this by animating the margin-left CSS property with jQuery. I specified a size for the .slider class and used overflow: hidden; to ensure the sliding images were not displayed outside of it.
If you wish, you can change the transition effect by changing the CSS property that is animated and ensuring that the elements are in the correct position for the animation before it begins.
You can also change the speed of the animation by changing the magic number 1000 that I've left in the calls to animate. This number is specified in milliseconds.
By the way, I should point out that while custom HTML attributes are allowed in HTML5 they should begin with data-; they are called data attributes.
jsfiddle
HTML
<div id="sldvid1" class="slider">
<img class="active" data-slide-to="0" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png"/>
<img data-slide-to="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png"/>
<img data-slide-to="2" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png"/>
</div>
<hr>
<div id="sldvid2" class="slider">
<img class="active" data-slide-to="0" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail1.png"/>
<img data-slide-to="1" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail7.png"/>
<img data-slide-to="2" src="https://s3.amazonaws.com/qa.SentientPrime.media/Ecommerce/44c068f106659d396f1ea0f2401f3879/1/thumbnail14.png"/>
</div>
CSS
.slider {
position: relative;
width: 50px;
height: 50px;
overflow: hidden;
}
.slider img {
display: none;
width: 100%;
position: absolute;
}
.slider .active {
display: inline-block;
}
.slider .sliding {
display: inline-block;
}
JavaScript
var timer = setInterval(runSlide, 2000);
function runSlide() {
// Slide each slider on the page.
$(".slider").each(function (index, element) {
// Get the elements involved in the slide.
var numChildren = $(this).children().length;
var activeChild = $(this).children(".active");
var activeSlideTo = $(activeChild).attr("data-slide-to");
var nextSlideTo = (parseInt(activeSlideTo) + 1) % numChildren;
var nextChild = $(this).find("*[data-slide-to=" + nextSlideTo + "]");
// Prepare for slide.
$(activeChild).css("margin-left", "0%");
$(nextChild).css("margin-left", "-100%");
$(activeChild).addClass("sliding");
$(nextChild).addClass("sliding");
$(activeChild).removeClass("active");
// Slide using CSS margin-left.
$(activeChild).animate({"margin-left": "100%"}, 1000, function () {
$(this).removeClass("sliding");
});
$(nextChild).animate({"margin-left": "0%"}, 1000, function () {
$(this).addClass("active");
$(this).removeClass("sliding");
});
});
}
Ended with following
setInterval(function() {
$('#sldvid1 > img:first')
.fadeOut(1000)
.next()
.fadeIn(1000)
.end()
.appendTo('#sldvid1');
}, 3000);

show images one by one using fadein and fadeout in jquery

Today while creating a slider i stuck in the middle of code that how can i fadein and fadeout the image one by one in jquery. Code i tried so far:-
<head>
<style>
#slideshow{
list-style: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
padding: 0;
margin: 0;
position:fixed;
}
ul{
list-style-type:none;
}
ul li{
display:inline;
width: 100%;
height: 100%;
position:absolute;
background-size:cover;
background-position:center center;
}
ul li img{
display:none;
}
</style>
</head>
<body>
<ul id="slideshow">
<li><img src="img/1.jpg" /></li>
<li><img src="img/2.jpg" /></li>
<li><img src="img/3.jpg" /></li>
</ul>
<script>
window.onload=init;
function init(){
items=$('ul').children('li');
i=0;
item=$(items[i]);
item.css('background-image','url('+ item.find('img').attr('src') +')').fadeOut(1000,function(){
for(i=0;i<items.length;i++){
item=$(items[i]);
item.css('background-image','url('+ item.find('img').attr('src') +')');
}
});
}
</script>
</body>
After showing first image it automatically goes to last image without displaying the second image.
Please help me to rectify this problem.
Here's how you can do it: JSFiddle
function init(){
$("#slideshow li").each(function(index){
this.style.backgroundImage = "url('" + this.children[0].src + "')";
if( index != 0)
this.style.display = "none";
});
setTimeout(changeImage, 4000);
}
function changeImage(){
$curr = $("#slideshow .active");
$next = $("#slideshow .active").next();
if($next[0] === undefined)
$next = $("#slideshow li").eq(0);
$curr.fadeOut(1000, function(){
$next.fadeIn(1000, function(){
$curr.removeClass("active");
$next.addClass("active");
setTimeout(changeImage, 4000); //change image every 4 seconds
});
});
}
$(document).ready(init);
You need to use the setInterval() and something must tell you what is the current img. Assume that all image is hidden exept for the active one.
<ul id="slideshow">
<li class="active"><img src="img/1.jpg" /></li>
<li><img src="img/2.jpg" /></li>
<li><img src="img/3.jpg" /></li>
</ul>
function ShowNext()
{
var current = $("#slideshow .active");
$(current).removeClass("active");
$(current).fadeOut(1000, function () {
$(current).next().fadeIn(1000);
$(current).next().addClass("active");
});
}
setInterval(function() {
ShowNext();
}, 4000);
Code not tested but this is how you should do it. Also you need to do something when you reach the end of the slider but i'm sure you can handle that.
I'd suggest having a single element instead of 3.
Also, use a recursive function to swap the image every 2 seconds.
Lastly note the javascript has been moved inside the <head> element where it should be.
Update: This has been tested and works great - had to fix a few bugs - here's the updated code:
<html>
<head>
<style><!-- Your Styles --></style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script language="javascript">
var imgNum = 1;
$(document).ready(function() {
doSlideshow();
});
function doSlideshow() {
$('#image1').fadeOut(400, function() {
$('#image1').attr('src', 'img/' + imgNum + '.jpg');
$('#image1').fadeIn(400);
imgNum++;
if (imgNum == 4) { imgNum = 1; }
setTimeout('doSlideshow()', 2000);
});
}
</script>
</head>
<body>
<ul id="slideshow">
<li><img id="image1" src="" /></li>
</ul>
</body>
</html>
There are definitely more than one way to do this.
I answered a similar question here:
>> Adding fade to simple slideshow with Javascript <<
However, to answer YOUR question directly, consider the following:
>> WORKING JS FIDDLE <<
// create arbitrary namespace
window.slideshow = {
slides: null,
currentSlide: null,
nextSlide: null,
interval: 3000,
timer: null,
init: function() {
console.log('init slideshow');
this.slides = $('#slideshow img');
this.planNextSlide(1);
},
planNextSlide: function(timeoutInterval) {
console.log('next slide (' + timeoutInterval + ')');
this.timer = setTimeout(this.transitionSlide, timeoutInterval);
},
transitionSlide: function() {
console.log('transition slide (' + (slideshow.currentSlide != null) + ')');
if (slideshow.currentSlide != null) {
// fade out old slide first
slideshow.slides.eq(slideshow.currentSlide).fadeOut('fast', function() {
slideshow.nextSlide = slideshow.currentSlide + 1;
if (slideshow.nextSlide == slideshow.slides.size()) {
slideshow.nextSlide = 0;
}
slideshow.currentSlide = null;
slideshow.transitionSlide();
});
}
else {
// fade in new slide
slideshow.nextSlide = slideshow.nextSlide == null ? 0 : slideshow.nextSlide;
slideshow.slides.eq(slideshow.nextSlide).fadeIn('fast', function() {
slideshow.currentSlide = slideshow.nextSlide;
slideshow.planNextSlide(slideshow.interval);
});
}
}
};
// initial state initializer
slideshow.init();

Categories