I have made this minimal test jsfiddle to show images and navigate with thumbnails, next and previous and also run as a slideshow.
It seems to be working OK, except that I can not get the current displayed image to fadeOut prior to the fadeIn of the next image.
Initially all the images were placed in a stack in the #holder DIV and then FadeIn and FadeOut worked as I expected, but I need to have the images in an array and load as required, because there will be several different values, associated with each image.
I probably have made some fundamental mistake or I do not understand how FadeIn and FadeOut properly work, as I am not an expert in javascript and jquery and I just get by, by looking at examples on here and similar sites.
I suspect I may need to somehow force a delay before loading the next image, but I can not work out how to do that.
Thanks
<style type='text/css'>
#holder { position: absolute; top: 100px; background-color:#CCCCCC;
width: 300px; height: 200px;
}
.slides { position: relative; top: 0px;
display: none;
}
#thumbs li
{
display: inline;
list-style-type: none;
padding-right: 6px;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
// define Global Vars
var timerON = null;
var files = [
["http://dummyimage.com/300x200/000/fff&text=Array-01", "http://dummyimage.com/40x40/000/fff&text=01","Title-01"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-02", "http://dummyimage.com/40x40/000/fff&text=02","Title-02"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-03", "http://dummyimage.com/40x40/000/fff&text=03","Title-03"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-04", "http://dummyimage.com/40x40/000/fff&text=04","Title-04"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-05", "http://dummyimage.com/40x40/000/fff&text=05","Title-05"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-06", "http://dummyimage.com/40x40/000/fff&text=06","Title-06"] ,
["http://dummyimage.com/300x200/000/fff&text=Array-07", "http://dummyimage.com/40x40/000/fff&text=07","Title-07"]
]
var numImages = files.length;
// initial routines
showImage(1);
buildThumbs();
function showImage(num) {
//$('#holder img').fadeOut();
if ( $('#holder img').length > 0 ) { // fadeout existing
$("#holder img").fadeOut(700);
//alert("Faded OUT");
}
$("#holder").html('<img id="' + num + '" src="' + files[num-1][0] + '" style="display:none;"' + '" />');
$("#holder img").fadeIn(700);
//alert("Faded IN");
}
function buildThumbs() {
var thumbs = "";
for (cnt=0; cnt<files.length; cnt++) {
thumbs += '<li><a href="#" id="' + (cnt + 1) + '"><img src="' + files[cnt][1] + '" /></li>';
}
$('#thumbs').html(thumbs);
}
// Initialise routines for acting on click events
$(document).ready(function() {
$('#prev').click( function () {
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == 1) {
// at first position
}
else {
showImage(currImage-1); }
});
$('#next').click( function () {
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == numImages) {
// at last position
}
else {
showImage(currImage+1);
}
});
$('#thumbs a').click( function () {
var selImage = parseInt($(this).attr('id'));
var currImage = parseInt($('#holder img:visible').attr("id"));
showImage(selImage);
});
$('#slideShowBtn').click( function () {
slideShowCheck();
});
});
function slideShowCheck() {
if(timerON != null) {
clearTimeout(timerON);
timerON = null;
$('#slideShowBtn').text('Play Slideshow');
} else {
$('#slideShowBtn').text('Stop Slideshow');
slideShow();
}
}
function slideShow() {
var nextImage = 0;
var currImage = parseInt($('#holder img:visible').attr("id"));
if (currImage == numImages) {
nextImage = 1;
} else {
nextImage = currImage + 1;
}
showImage(nextImage);
timerON = setTimeout(slideShow, 3000);
}
});//]]>
</script>
</head>
<body>
<p>
<button id="prev">« Prev</button>
<button id="next">Next »</button>
</p>
<ul id="thumbs">
</ul>
<p>
<button id="slideShowBtn">Play Slideshow</button>
</p>
<div id="holder">
</div>
<div style="clear:both;"></div>
<ul id="thumbs2">
</ul>
</body>
</html>
Callbacks, callbacks, callbacks.
JS does alot of things async, so you will need to make use of a callback on that fadein.
$(ITEM1).fadeOut("fast", function() {
alert("all the way faded out");
$(ITEM2).fadeIn("fast");
});
Here's your fixed fiddle.
Related
I'm trying to make a carousel that after 3 seconds changes image.
I got 3 images as slide1, slide2, slide3
and thanks to the methods change1,change2,change3 changes image.
I would like to automate everything like this:
function time(change1, change2, change3) {
this.change1 = change1;
this.change2 = change2;
this.change3 = change3;
t = setInterval(change1 && change2 && change3, 3000); //obviously it doesn't work.
}
/*
---------------ANOTHER METHOD-----------------
*/
function time() {
t = setInterval(check, 3000);
}
function check() {
if (slide1.style.display = "inline-block") {
change2();
} else if (slide2.style.display = "inline-block") {
change3();
} else {
change1();
}
}
but i don't know how
Any ideas?
well that is an easy job, here is a simple example on how you could do it
I used jq but you will get the idee. if you want only js that let me know will do it to
/// use jq for batter effekt
var sliders = $(".container > div");
var current;
function change() {
if (!current)
current = sliders.first();
else {
current.hide("fast");
current = current.next();
}
if (current.length == 0)
current = sliders.first();
current.show();
}
setInterval(change, 2000);
.container {
display: flex;
border: 1px solid #CCC;
}
.container>div {
width: 100%;
min-height: 100px;
}
.container>div:not(:first-child){
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div style="background:red;"></div>
<div style="background:green"></div>
<div style="background:blue"></div>
</div>
My slider is allowing for content to go forwards and backwards when the Next/Previous links are clicked. When I switch the contentType to 'div' it only shows content in slides 1 and 3. Could someone please explain why the counter is not incrementing properly? Is there a more effecient way to do this? I have included my code below as well as a working example. The purpose of this script is to allow for images or content to be displayed in a slide. Any help is much appreciated!
$(document).ready(function() {
// VARIABLE DECLARATIONS
var $el = $('#showcase');
var $leftArrow = $('#left_arrow');
var $rightArrow = $('#right_arrow');
var contentType = $('div'); // change to img and reverse comment out HTML code
var slideCount = $el.children().length;
var slideNum = 1;
var $load = $el.find(contentType)[0];
// PRELOADS SLIDE WITH CORRECT SETTINGS
$load.className = 'active';
$leftArrow.addClass("disabled");
// CHECKS FOR FIRST AND LAST INDEX
function checkSlide() {
if (slideNum == 1) {
$leftArrow.addClass('disabled');
} else {
$leftArrow.removeClass('disabled');
}
if (slideNum == slideCount) {
$rightArrow.addClass('disabled');
} else {
$rightArrow.removeClass('disabled');
}
}
// NAVIGATIONAL LOGIC FOR PREVIOUS/NEXT BUTTONS
$leftArrow.click(function() {
if (slideNum > 1) {
var counter = $(".active").index();
counter--;
$('.active').addClass('slide');
$('.active').removeClass('active');
contentType.eq(counter).addClass('active');
slideNum--;
checkSlide();
console.log('slideNum: ' + slideNum);
console.log('counter: ' + counter);
}
})
$rightArrow.click(function() {
if (slideNum < slideCount) {
var counter = $(".active").index();
counter++;
$('.active').addClass('slide');
$(".active").removeClass('active');
contentType.eq(counter).addClass('active');
slideNum++;
checkSlide();
console.log('slideNum: ' + slideNum);
console.log('counter: ' + counter);
}
})
});
img {
width: 160px;
}
a {
color: blue;
}
.disabled {
color: red !important;
}
.slide {
display: none;
}
.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- <div id="showcase">
<img class="slide" src="https://picsum.photos/458/354" />
<img class="slide" src="https://picsum.photos/458/354/?image=306" />
<img class="slide" src="https://picsum.photos/458/354/?image=626" />
</div>
« Previous
Next » -->
<div id="showcase">
<div class="slide">Page 1 content</div>
<div class="slide">Page 2 content</div>
<div class="slide">Page 3 content</div>
</div>
« Previous
Next »
The issue is that your "contentType" var, which matches divs, also matches the "showcase" div, so you are getting 4 in your list, not 3 as you expect. In your left/right arrow click handlers, replace:
contentType.eq(counter).addClass('active');
with:
$el.find(contentType).eq(counter).addClass('active');
I have an animation which is called using onmousedown. I have another function which stops the animation (onmouseup).
The problem is that it only works the first time. By that I mean when I hold the button, it works and then stops when I stop pressing down but if I try to use either of the buttons after that first time nothing happens. It just won't move.
This is my HTML code (index.htm):
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<img id='player' src='img/player.png' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)"><--</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">--></button>
</div>
</body>
</html>
<script type='text/javascript' src='move.js'></script>
This is my javascript code (move.js):
var elem = document.getElementById("player");
function OnButtonDownl (button) {
var posl = document.getElementById("player").style.left;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
}}
function OnButtonUpl (button) {
clearInterval(idl);
}
var elem = document.getElementById("player");
function OnButtonDownr (button) {
var posr = document.getElementById("player").style.left;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
}}
function OnButtonUpr (button) {
clearInterval(idr);
}
Probably not important but here is my css (style.css):
body {
width: 100%;
height: 100%;
position:relative;
margin:0;
overflow:hidden;
}
#player {
position: absolute;
left:0;
bottom:0;
}
.buttons {
position:absolute;
right:0;
bottom:0;
}
Thanks for any help in advance.
You're running into 2 issues.
When you first get posl and posr, you're getting an empty string that JS is coercing to 0.
The -- and ++ won't work after you append the px (thus making posl and posr into string values)
Your posl-- (and posr++) can increment that coerced 0. That's why it works the first time through. The next time you mousedown the document.getElementById("player").style.left is a string — like "-1px" — that isn't interpreted as falsy (won't be coerced into 0). You can get around that by using parseInt() when you cache posl|posr but you have to provide a fallback of 0 because parseInt("") returns NaN…
You can work around that like so (with similar changes when you get posr):
var posl = parseInt( document.getElementById("player").style.left, 10 ) || 0;
var elem = document.getElementById("player");
function OnButtonDownl(button) {
//var posl = document.getElementById("player").style.left;
var posl = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idl = setInterval(framel, 5);
function framel() {
posl--;
elem.style.left = posl + 'px';
}
}
function OnButtonUpl(button) {
clearInterval(idl);
}
var elem = document.getElementById("player");
function OnButtonDownr(button) {
//var posr = document.getElementById("player").style.left;
var posr = parseInt(document.getElementById("player").style.left, 10) || 0;
window.idr = setInterval(framer, 5);
function framer() {
posr++;
elem.style.left = posr + 'px';
}
}
function OnButtonUpr(button) {
clearInterval(idr);
}
body {
width: 100vw;// changed for example only
height: 100vh;// changed for example only
position: relative;
margin: 0;
overflow: hidden;
}
#player {
position: absolute;
left: 0;
bottom: 0;
}
.buttons {
position: absolute;
right: 0;
bottom: 0;
}
<img id='player' src='//placekitten.com/102/102' />
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDownl (this)" onmouseup="OnButtonUpl (this)">Left</button>
<button id='moveright' onmousedown="OnButtonDownr (this)" onmouseup="OnButtonUpr (this)">Right</button>
</div>
I was rewrite your code and it work (for me).
function Move(elem){
this.interval;
var posr = parseInt(getComputedStyle(document.getElementById("player")).left);
this.handleEvent = function(event) {
switch (event.type) {
case 'mousedown':
this.interval = setInterval(function() {
if (event.target.id == 'moveright') {
posr++;
} else if (event.target.id == 'moveleft'){
posr--;
}
document.getElementById("player").style.left = posr + 'px';
},5);
break;
case 'mouseup':
clearInterval(this.interval);
break;
}
}
elem.addEventListener('mousedown', this, false);
elem.addEventListener('mouseup', this, false);
}
var button_right = document.getElementById("moveright");
var button_left = document.getElementById("moveleft");
Move(button_right);
Move(button_left);
And in html you can remove js event listeners (this need only id).
First of all it is good practice to put your script tag inside your html tags:
<html>
<head>...</head>
<body>...</body>
<script type='text/javascript' src='move.js'></script>
</html>
Done that check this solution:
HTML:
<html>
<head><link rel='stylesheet' href='style.css'></head>
<body>
<img id='player' src='https://placeimg.com/54/45/any' style='height:64px;'></img>
<div class='buttons'>
<button id='moveleft' onmousedown="OnButtonDown('left')" onmouseup="OnButtonUp()"><--</button>
<button id='moveright' onmousedown="OnButtonDown('right')" onmouseup="OnButtonUp()">--></button>
</div>
<script type='text/javascript' src='move.js'></script>
</body>
</html>
And js:
var nIntervId;
var b;
var elem = document.getElementById("player");
var posl = document.getElementById("player").style.left;
function OnButtonDown(button) {
b = button;
nIntervId = setInterval(frame, 5);
}
function frame() {
if(b==='left'){
posl--;
elem.style.left = posl + 'px';}
else{
posl++;
elem.style.left = posl + 'px';
}
}
function OnButtonUp() {
clearInterval(nIntervId);
}
http://output.jsbin.com/varaseheru/
I would like to create a little slider to change background-image of my div every seconds.
My code doesn't work for the moment, image is not changed. And ideally, i would like that the script run in infinite mode..
HTML
<div id="slidesPartenairesHome"></div>
CSS
#slidesPartenairesHome {
background-size: contain;
background-position: center center;
width: 300px;
height: 170px;
margin-left: 120px;
}
JS
$( document ).ready(function() {
var arrayOfPartenaires = [
"images/partenaires/a.png",
"images/partenaires/b.jpg",
"images/partenaires/c.jpg",
"images/partenaires/d.png",
"images/partenaires/e.png",
"images/partenaires/f.jpg",
"images/partenaires/g.jpg",
"images/partenaires/h.jpg",
"images/partenaires/i.png",
"images/partenaires/j.jpg",
"images/partenaires/k.jpg",
"images/partenaires/l.jpg"
];
for (var i=0; i<arrayOfPartenaires.length; i++) {
var currentPartenaireImg = arrayOfPartenaires[i];
$('#slidesPartenairesHome').animate({opacity: 0}, 'slow', function() {
$(this).css({'background-image': 'url("'+currentPartenaireImg+')'}).animate({opacity: 1});
});
}
});
You could use window.setinterval, you could also use setTimeout but setinterval is a litle bit more precise.
Example with setinteval:
window.setInterval(function(){
var url = getCurrent();
//start animation
$('#slidesPartenairesHome').delay( 500 ).fadeTo(500, 0.3, function()
{
$(this).css('background-image', 'url(' + url + ')');
}).fadeTo('slow', 1);
}, 1000);
// We start with index of 1 because we want to skip the first image,
// Else we would be replacing it with the same image.
var index = 1;
var arrayOfPartenaires = [
"http://yourdomain.com/images/partenaires/a.png",
"http://yourdomain.com/images/partenaires/b.png",
"http://yourdomain.com/images/partenaires/c.png"
];
function getCurrent(){
// We check if the index is higher than the ammount in the array.
// If thats true set 0 (beginning of array)
if (index > arrayOfPartenaires.length -1){
index = 0;
}
var returnValue = index;
index ++;
return arrayOfPartenaires[returnValue];
}
Note if you really want to change the image every 1 second the background will be changing very fast.
Fiddle
I hope this may help you
html
<div id="slidesPartenairesHome">
<div id="imags">
</div>
</div>
Css
#slidesPartenairesHome
{
margin-left: 120px;
}
#slidesPartenairesHome, #imags
{
background-size: contain;
background-position: center center;
width: 300px;
height: 170px;
}
Js
$(function () {
var arrayOfPartenaires = [
"http://fotos2013.cloud.noticias24.com/animales1.jpg",
"http://www.schnauzi.com/wp-content/uploads/2013/03/animales-en-primavera.jpg",
"https://johannagrandac.files.wordpress.com/2015/01/conejos.jpg",
"http://png-4.findicons.com/files/icons/1035/human_o2/128/face_smile.png",
"http://icons.iconarchive.com/icons/rokey/the-blacy/128/big-smile-icon.png",
"http://simpleicon.com/wp-content/uploads/smile-256x256.png"
];
var loaders = 0;
function cycleImages() {
var element = arrayOfPartenaires[loaders];
$("#imags").css({ 'background-image': 'url(' + element + ')' }).animate({ opacity: 1 }).hide().fadeIn("slow");
if (loaders < arrayOfPartenaires.length) {
loaders = loaders + 1;
if (loaders >= arrayOfPartenaires.length) {
loaders = 0;
}
}
else {
loaders = 0;
}
console.log(loaders, arrayOfPartenaires[loaders]);
}
cycleImages();
setInterval(function () { cycleImages() }, 3000);
});
jsFiddel Demo
I am working on a wordpress website who's client would like me to adjust our AdSanity plugin to display groups of ads in a rotating image gallery fashion like the ones on this page. The leaderboard ads for sure are AdSanity run. I was able to stem from viewing the source that this is the script I need:
$(function() {
var adsLists = $('.adsanity-group'),
i = 0;
var divs = new Array();
adsLists.each(function() {
divs[i] = $("#" + $(this).attr('id') + " div").not(".clearfix").hide();
i++;
});
var cycle_delay = 12000;
var num_groups = $('.adsanity-group').length;
function cycle(divsList, i) {
divsList.eq(i).fadeIn(400).delay(cycle_delay).fadeOut(400, function() {
cycle(divsList, ++i % divsList.length); // increment i, and reset to 0 when it equals divs.length
});
};
for (var j = divs.length - 1; j >= 0; j--) {
if (divs[0].eq(0).attr('num_ads') > 1)
cycle(divs[j], 0);
else
divs[j].show();
};
//////////
$('#slides').slidesjs({
width: 552,
height: 426,
navigation: false,
play: {
auto: true
}
});
//////////
$('.three_lines_fixed').each(function() {
$clamp(this, {
clamp: 3
});
});
var top_divs = $("#adspace div").not(".clearfix").hide(),
top_i = 0;
var top_num_ads = $('#adspace > div').attr("num_ads");
var top_cycle_delay = 12000;
function top_cycle() {
top_divs.eq(top_i).fadeIn(400).delay(top_cycle_delay).fadeOut(400, top_cycle);
top_i = ++top_i % top_divs.length; // increment i,
// and reset to 0 when it equals divs.length
};
if (top_num_ads > 1) {
top_cycle();
} else {
top_divs.show();
}
var site_url = $("body").attr("site_url");
$("#brpwp_wrapper-2 ul").append("<li style='text-align: center;'><a class='widgetized_read_more' href='" + site_url + "/2013'>Read More</a></li>")
/**/
And some of that I don't believe I need, like the three_lines_fixed or the slides. I also have the CSS used for #adspace:
div.header div#adspace {
float: right;
max-width: 728px;
max-height: 90px; }
div.header div#adspace img {
float: right; }
There is also this CSS:
div#page .main_content ul.widgets li.adspace {
display: none; }
On my site http://dsnamerica.com/eisn/ I want the 300px width ads on the right sidebar to rotate like those on the Vype site. These ads though are not listed with ul and li, they are divs.
So far I've added this to my header.php theme file right before the closing tag:
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/fading-ads.js"></script>
And in that file (js/fading-ads.js), I have this:
function adsanitygroup() {
var adsLists = $('.adsanity-group'),
i = 0;
var divs = new Array();
adsLists.each(function() {
divs[i] = $("#" + $(this).attr('id') + " div").not(".clearfix").hide();
i++;
});
var cycle_delay = 12000;
var num_groups = $('.adsanity-group').length;
function cycle(divsList, i) {
divsList.eq(i).fadeIn(400).delay(cycle_delay).fadeOut(400, function() {
cycle(divsList, ++i % divsList.length); // increment i, and reset to 0 when it equals divs.length
});
};
for (var j = divs.length - 1; j >= 0; j--) {
if (divs[0].eq(0).attr('num_ads') > 1)
cycle(divs[j], 0);
else
divs[j].show();
var top_divs = $("#adspace div").not(".clearfix").hide(),
top_i = 0;
var top_num_ads = $('#adspace > div').attr("num_ads");
var top_cycle_delay = 12000;
function top_cycle() {
top_divs.eq(top_i).fadeIn(400).delay(top_cycle_delay).fadeOut(400, top_cycle);
top_i = ++top_i % top_divs.length; // increment i,
// and reset to 0 when it equals divs.length
};
if (top_num_ads > 1) {
top_cycle();
} else {
top_divs.show();
};
};
}
That is my attempt to define the function and clean out what I didn't need. I don't think, no, I know it's not right. So I'll put my questions in a list, since this post is already wordy.
1) Did I link the js file correctly in the theme's header.php file? It's right before the closing </head> tag.
2) Do I need the second CSS part that says "display: none" and if so, how do I change the CSS to work with divs instead of ul and li? Do I just change div#page .main_content ul.widgets li.adspace {
display: none;}
to
div#page .main_content .widgets .adspace {
display: none; }
then add the class .adspace to the widget?
See, I have been trying to get this to work for a couple days now and I've thought so much on it I'm not making cohesive theories anymore, just shots in the dark. How to solve this?