Select top 3 values from variable, then next 3 etc - javascript

I have this variable with images. I also have 3 div's in which I want to put the images.
var images = [
'dali.jpg',
'illusionisme.png',
'impresionisme.jpg',
'popart.jpg',
'abstracter.jpg',
'abstrat.jpg',
'concept.jpg',
'fingerpaint.jpg',
'flowers.jpg',
'graffiti.jpg',
'groovy.jpg',
'skelly.jpg',
'vangogh.jpg'
]
By using this code every div does get a random image, which is nice but not what I want. How can I use jQuery to put the first 3 images inside the 3 divs, then the second 3 images in the div?
$(".art").click(function(){
$(".art").each(function(){
$(this).find("img").remove();
$(this).prepend('<img src="assets/images/' + images[Math.floor(Math.random()*images.length)] + '">');
});
});
<div class="art">
<div class="art">
<div class="art">

Not sure what you mean, please elaborate if this is not what you are looking for..
http://jsfiddle.net/jFIT/c7U7q/1/
where the code is giving just text now, you can wrap that text in an <img src= /> to give you the images..
var images = [
'dali.jpg',
'illusionisme.png',
'impresionisme.jpg',
'popart.jpg',
'abstracter.jpg',
'abstrat.jpg',
'concept.jpg',
'fingerpaint.jpg',
'flowers.jpg',
'graffiti.jpg',
'groovy.jpg',
'skelly.jpg',
'vangogh.jpg'];
$(".art").click(function () {
$(this).html(getNext3()); //images[Math.floor(Math.random()*images.length)]);
});
$('#startLoop').click(function () {
loopImages();
});
function loopImages(){
var art = $('.art');
art.fadeOut(1000, function () {
art.html(getNext3()).fadeIn(1000, function() { loopImages(); });
});
}
var counter = 0;
function getNext3() {
var imgs = "";
//img src=...
for (i = 0; i < 3; i++) {
imgs += ' ' + images[counter];
counter++;
}
return imgs;
}
UPDATED
(load 3 into 3 divs at a time.)
http://jsfiddle.net/jFIT/c7U7q/7/
function setNext3() {
var imgs = "";
//img src=...
for (i = 0; i < 3; i++) {
imgs = images[counter];
console.log(imgs);
console.log(i);
$("div.art:nth-child(" + (i + 1) + ")").html(imgs);
console.log($("div.art:nth-child(" + i + ")"));
counter++;
}
}

You can keep track of the current image index and then add the number to increase the index by each click
html
<div class="art">
<img data-imageindex="0" src="" />
</div>
<div class="art">
<img data-imageindex="1" src="" />
</div>
<div class="art">
<img data-imageindex="2" src="" />
</div>
js
var artLength = $(".art").length;
$(".art").click(function () {
$(".art").each(function () {
var $image = $(this).find("img");
var nextImageIndex = $image.data("imageindex") + artLength;
if (nextImageIndex >= images.length) {
nextImageIndex -= images.length;
}
$image.data("imageindex", nextImageIndex).attr("src",
"assets/images/" + images[nextImageIndex]);
});
});
http://jsfiddle.net/44zB4/

Related

The image changes automatically - Start button

I wanted to add a button to start the change between images, to avoid the start of the change on its own
You must press the button until the change starts
var imageSources = ["https://www.w3schools.com/css/img_fjords.jpg", "https://www.w3schools.com/howto/img_mountains.jpg"]
var index = 0;
setInterval(function(){
if (index === imageSources.length) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
}, 2000);
<img id="image" src="https://www.w3schools.com/css/img_fjords.jpg" style="width:300px">
Hi Please have a look I hope it's helpful Thanks
https://jsfiddle.net/sanat/xc5w8ngy/7/
<button id="start">
start
</button>
<button id="stop">
stop
</button>
<br>
<br>
<img id="image" src="https://www.w3schools.com/css/img_fjords.jpg" style="width:300px">
var myVar = '';
$(function(){
$("#start").on('click',function(){
var imageSources = ["https://www.w3schools.com/css/img_fjords.jpg", "https://www.w3schools.com/howto/img_mountains.jpg"]
var index = 0;
myVar = setInterval(function(){
if (index === imageSources.length) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
}, 2000);
});
$("#stop").on('click',function(){
clearInterval(myVar);
});
});

Jquery How To Stop Append from Appending Previous Element

I'm having trouble to display the star of each hotel and not sure on how to do it. I have like 5 hotels, and each has different value of hotelStar.
My Javascript code:
function GetStarHotel() {
var parent = $(' p.star '),
imagePath = 'image/hotelstar.png',
img;
for (var i = 0; i < hotelStar; i++) {
img = new Image();
img.src = imagePath;
$(parent).append('<img src="image/hotelstar.png" class="hotelStar" />')
}
}
And my HTML Code is:
<h1>Hotel 1</h1>
<p class="star"><script>
hotelStar = 4;
GetStarHotel();
</script></p>
<h1>Hotel 2</h1>
<p class="star"><script>
hotelStar = 3;
GetStarHotel();
</script></p>
<h1>Hotel 3</h1>
<p class="star"><script>
hotelStar = 2;
GetStarHotel();
</script></p>
It is adding my previous Hotel's Stars. How can I prevent it from adding the same element?
Instead of append() you can use .html(), check updated code below
function GetStarHotel() {
var parent = $(' p.star '),
imagePath = 'image/hotelstar.png',
img,
star = '';
for (var i = 0; i < hotelStar; i++) {
img = new Image();
img.src = imagePath;
star += '<img src="'+imagePath +'" class="hotelStar" />';
}
$(parent).html(star)
}
i have simplified your code. check updated snippet below
$('p.star').each(function(){
count = $(this).data('star'),
star = '',
imagePath = 'http://www.freeiconspng.com/uploads/download-png-image-star-png-image-1.png';
for (var i = 0; i < count; i++) {
star += '<img src="'+imagePath +'" width="16" class="hotelStar" alt="'+i+'" />';
}
$(this).html(star)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Hotel 1</h1>
<p class="star" data-star ="4" ></p>
<h1>Hotel 2</h1>
<p class="star" data-star ="3"></p>
<h1>Hotel 3</h1>
<p class="star" data-star ="2"></p>

Using setTimeout inside a for loop - not working

I have a setTimeout inside the a for loop, but it not behaving as i anticipated.
I have a bunch of banners in a page that are loading all at once. I am removing their parent's div html and storing it in an array. Then I would like for each parent to receive its corresponding html every 5 seconds. This only needs to happen once on ready state.
Here's my code...
function oneBanner() {
var divs = $('.banner-slide'),
imgs = [];
for ( var j = 0; j < divs.length; j++ ) {
imgs.push( $('.banner-slide:nth-child(' + (j+1) + ')') );
}
for ( var k = 0; k < imgs.length; k++ ) {
var url = $(imgs[k]).html();
$(imgs[k]).html('');
setTimeout(function(y) {
console.log(k * 5000);
$(imgs[k]).html(url);
}, k * 5000, k);
}
}
oneBanner();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="banner-slide">
<img src="http://www.placecage.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://fillmurray.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://stevensegallery.com/150/150" >
</div>
As you can see the images do not get printed on the screen one at a time every 5 seconds - which I thought I was doing.
Thank you for any help.
Serge
It will be better to simplify your code while you don't need any of variables/arrays outside this function .. you can just use jquery .each()
try This
function oneBanner() {
var divs = $('.banner-slide');
divs.each(function(i){ // loop through .banner-slide divs
var ThisIt = $(this); // define this outside setTimout function
setTimeout(function(){
divs.hide(); // hide all .banner-slide divs
ThisIt.show(); // show just this one
} , 5000 * i); // time * the i -- i is the index of the div
});
}
see the code in action
function oneBanner() {
var divs = $('.banner-slide');
divs.each(function(i){
var ThisIt = $(this);
setTimeout(function(){
divs.hide();
ThisIt.show();
} , 5000 * i);
});
}
oneBanner();
.banner-slide:not(:first){
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="banner-slide">
<img src="http://www.placecage.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://fillmurray.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://stevensegallery.com/150/150" >
</div>
Note: by using setTimeout() you'll show each image for 5 seconds and the code will stop looping
Update up to the OP comment
function oneBanner() {
var divs = $('.banner-slide'),
htmlArray = [];
divs.each(function(i){
var ThisIt = $(this); // get this outside the setTimout
htmlArray.push(ThisIt.html()); // push the inner html to the array
ThisIt.html(''); // emty this div
setTimeout(function(){
$(ThisIt).html(htmlArray[i]); // add html again with setTimeout every 5 second to its parent div
} , 5000 * i);
});
}
oneBanner();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="banner-slide">
<img src="http://www.placecage.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://fillmurray.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://stevensegallery.com/150/150" >
</div>
one word: closure
function oneBanner() {
var divs = $('.banner-slide'),
imgs = [];
for ( var j = 0; j < divs.length; j++ ) {
imgs.push( $('.banner-slide:nth-child(' + (j+1) + ')') );
}
imgs.forEach(($img,k)=>{
var url = $img.html();
$img.html('');
setTimeout(function(y) {
$img.html(url);
}, k * 5000, k);
})
}
oneBanner();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="banner-slide">
<img src="http://www.placecage.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://fillmurray.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://stevensegallery.com/150/150" >
</div>
You are referencing the wrong variable inside of your setTimeout. Replace 'y' with 'k'
function oneBanner() {
var divs = $('.banner-slide'),
imgs = [];
for ( var j = 0; j < divs.length; j++ ) {
imgs.push( $('.banner-slide:nth-child(' + (j+1) + ')') );
}
for ( var k = 0; k < imgs.length; k++ ) {
var url = $(imgs[k]).html();
$(imgs[k]).html('');
setTimeout(function(k) {
console.log(k * 5000);
$(imgs[k]).html(url);
}, k * 5000, k);
}
}
oneBanner();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="banner-slide">
<img src="http://www.placecage.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://fillmurray.com/150/150" >
</div>
<div class="banner-slide">
<img src="http://stevensegallery.com/150/150" >
</div>

Prev and Next buttons switch images (links to images) in array???

These are the instructions:
"Have an image and two buttons, PREV and NEXT. Have 10 images in an array. When you click on NEXT, the next picture should display and when you click on PREV, the previous image should display."
This is what I wrote so far:
<html>
<head>
<title>Image Loop</title>
</head>
<body>
<img src="http://placekitten.com/500/200" id="image" style="height:150px; width:150px" />
<input type="button" value="Prev" name="previous_picture" onclick= nextImage();>
<input type="button" value="Next" name="next_picture"/>
<script>
function nextImage () {
var i = images.indexOf();
var imageSrc = document.getElementById("image").src=images[i];
for (i = weekdays.indexOf(day); i<weekdays.length; i++)
}
function prevImage () {
}
var images = new Array(
"http://placekitten.com/500/200",
"http://placekitten.com/499/200",
"http://placekitten.com/501/200",
"http://placekitten.com/500/199"
);
</script>
</body>
</html>
* the image should loop back around when it gets to the end of the array. I just don't know what I'm doing... :( *
Do some more investigations, this really shows too little effort.
I'll give you some pointers.
Javascript: Generic get next item in array
Javascript knows the modulus operation:
https://msdn.microsoft.com/nl-nl/library/9f59bza0(v=vs.94).aspx
prev = (index + length - 1 ) % length
next = (index + 1 ) % length
prev needs prevImage() and next needs nextImage() functions
etc.
Jsfiddle of a solution, using a small bit of jquery:
https://jsfiddle.net/cchhymtx/
Javascript:
var images = new Array(
"http://placekitten.com/500/200",
"http://placekitten.com/499/200",
"http://placekitten.com/501/200",
"http://placekitten.com/500/199");
function getCurrentImageIndex() {
return images.indexOf(document.getElementById("image").src);
}
function next() {
nextImage = (getCurrentImageIndex() + 1) % images.length;
document.getElementById("image").src = images[nextImage];
}
function prev() {
nextImage = (getCurrentImageIndex() - 1 + images.length) % images.length;
document.getElementById("image").src = images[nextImage];
}
You have a few things off here.
To start with, take a look at how Array.indexOf() works: http://www.w3schools.com/jsref/jsref_indexof_array.asp
What are you trying to attempt with:
for (i = weekdays.indexOf(day); i<weekdays.length; i++)
After you find the index of the picture that is current, if index+1 would be greater than or equal to the length of the images array, then set index to 0.
You can accomplish it by using the following code
<script language="JavaScript" type="text/JavaScript">
var imgArray = new Array(
"11011_1.jpg","11011_2.jpg","11011_3.jpg","11011_4.jpg","11011_5.jpg"
);
baseURL = "http://www.planet99.com/pix";
numImages = 5;
curImage = 1;
function f_slideshow( xflip ) {
curImage = curImage + xflip;
if (curImage > numImages)
{ curImage = 1 ; }
if (curImage == 0)
{ curImage = numImages ; }
document.images[2].src = baseURL + '/' + imgArray[curImage - 1];
}
</script>
Click on the buttons to flip through the photos - allow a few seconds for
each photo to load.
<input type="button" value="<< Prev" name="cb_prev"
onclick="f_slideshow(-1)">
<input type="button" value="Next >>" name="cb_next"
onclick="f_slideshow(1)">
<img src='http://www.planet99.com/pix/11011_1.jpg'>

how to link pagination to pagescroll in jquery?

I have created a carousel in javascript to show multiple contents either by using page scroll or by clicking a button. I have used viewpager.js for this purpose. I have added a pagination at the bottom which works fine when the buttons are clicked. I am unable to figure out how to link it to the page scroll. Any help is appreciated. My code:
HTML
<div id='prev'>
<button id="btn-prev"><img src='img/orange-towards-left.png'></button>
</div>
<div class='pager'>
<div class='pager_items' id='info'>
</div>
</div>
<div id='next'>
<button id="btn-next"><img src='img/orange-towards-right.png'></button>
</div>
<div id='pagination'>
<ul></ul>
</div>
JS
item_container = document.querySelector('.pager_items');
view_pager_elem = document.querySelector('.pager');
w = view_pager_elem.getBoundingClientRect().width;
items = payerAccArr.length;
item_container.style.width = (items * 100)+ '%';
var child_width = (100 / items) + '%';
var html = "";
document.getElementById('monthInfo').innerHTML=payerAccArr[0].DateKey + " Bill Amount ";
for (var i = 0; i < items; i++) {
html += "<div class=toggle><h4>Payer Account Name</h4> <ul> <li>" + payerAccArr[i].PayerAccountName +
"</li></ul> _______________ <ul><li> "+(payerAccArr[i].TotalAmount).toFixed(2) +
" USD</li> </ul></div>";
}
item_container.innerHTML = html;
for(var i=0;i<items;i++)
item_container.children[i].style.width = child_width;
var htmlStr='<li class="current"></li>';
for(var i=0;i<items-1;i++){
htmlStr += '<li></li>';
}
$('#pagination ul').html(htmlStr);
vp = new ViewPager(view_pager_elem, {
pages: item_container.children.length,
vertical: false,
onPageScroll : function (scrollInfo) {
offset = -scrollInfo.totalOffset;
invalidateScroll();
},
onPageChange : function (page) {
document.getElementById('monthInfo').innerHTML=payerAccArr[page].DateKey + " Bill Amount ";
}
});
window.addEventListener('resize', function () {
w = view_pager_elem.getBoundingClientRect().width;
invalidateScroll();
});
document.getElementById('btn-prev').addEventListener('click', function (){
vp.previous();
if(index>0){
createDoughnutChart(index--);
}
var li = jQuery("li.current");
if (li.length){
var $prev = li.prev();
if($prev.length == 0)
$prev = $("#pagination li").last().addClass("current");
li.removeClass("current");
$prev.addClass("current");
}
});
Similar code for the next button also has been written.
This issue got solved. I made a change to the onPageChange function by adding the following code. I am now able to link it to both the page scroll and the buttons.
JS:
onPageChange : function (page) {
document.getElementById('monthInfo').innerHTML=payerAccArr[page].DateKey + " Bill Amount ";
// console.log('page', page);
var li = $("li.current");
var curIndex = li.index();
if(li.length){
var $prev = li.prev();
var $next = li.next();
if(page == $prev.index()){
li.removeClass("current");
$prev.addClass("current");
}
if(page==$next.index()){
li.removeClass("current");
$next.addClass("current");
}
}
}

Categories

Resources