Image slider hover stop and animated transition - javascript

I was testing out coding an image slider as a project to learn HTML, CSS and Javascript and it works great. I'd just like to implement a few tweaks on it and was wondering if anyone had any idea on how to do this. Bear in mind, I'm relatively new to this so a few explanatory comments would be greatly appreciated.
Here are the tweaks I'd like to implement: When the user hovers over the image, I'd like the slider to stop on that particular image so the user can look at it for as long as they wish. The slider resumes once the mouse is moved (a topic not explored on any questions here as far as I can find). Another thing I'd like to be able to do is create a more aesthetic fade transition between the images. There are tutorials out there for this but they don't give a lot of context for a beginner like me to implement it. Here's the jsfiddle, as requested, http://jsfiddle.net/7m9j0ttL/
<html>
<head>
<style type="text/css">
.container {
max-width: 400px;
background-color: black;
margin: 0 auto;
text-align: center;
position: relative;
}
.container div {
background-color: white;
width: 100%;
display: inline-block;
display: none;
}
.container img {
width: 100%;
height: auto;
}
</style>
</head>
<body>
<section class="demo">
<div class="container">
<div style="display: inline-block;">
<img src="Chrysanthemum.jpg" width="1024" height="768" />
</div>
<div>
<img src="Desert.jpg" width="1024" height="768" />
</div>
<div>
<img src="Hydrangeas.jpg" width="1024" height="768" />
</div>
</div>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
var currentIndex = 0,
items = $('.container div'),
itemAmt = items.length;
function cycleItems() {
var item = $('.container div').eq(currentIndex);
items.hide();
item.css('display', 'inline-block');
}
var autoSlide = setInterval(function() {
currentIndex += 1;
if (currentIndex > itemAmt - 1) {
currentIndex = 0;
}
cycleItems();
}, 9000);
});
</script>
</body>
</html>

Updated your fiddle
$('.demo').hover(function(){
clearInterval(autoSlide);
},function(){
autoSlide = setInterval(function() {
currentIndex += 1;
if (currentIndex > itemAmt - 1) {
currentIndex = 0;
}
cycleItems();
}, 1000);
});
Added a hover handler to the .demo element. Cleared interval on hover, this would help stop the slide show. And re-set interval on mouseout to start the slideshow per the set interval.

I don't know whether such kind of answer is acceptable for you, but someday, a few years ago, I created my own slider when I was studying jquery.
Looking at your code, I have questions:
1. Why don't you use rather standard functions like fadeIn() and fadeOut() for transitions?
2. Why don't you make a function that will be able to run simultaneously with any number of tags on the page?
A few years ago I had these questions in my head and I came here, to stackoverflow to learn how to do that from other people. And I learnt (not only here, though).
And I created a function that could be loaded anywhere in the code - I studied how to do that. Then I added fade and slide effects there and also any other things...
This function is not really good, but PROBABLY it will sched some light for you in slider creation process. Sorry for many words, check what I have here:
https://jsfiddle.net/7m9j0ttL/3/
I hope my effort is useful for you. If you are going to go further with this and have questions - I would be glad to answer them.
Last comments:
So my main aim was to create function that could be ran like this:
$('.container').okwbSlider({ActAsDefined: 'fadeItOut', SlidingTag: 'div', timeOut: 3000});
so, here you can see that almost ANY tag, containing ANY other tags (with images, text etc in it) can be slided.
in order to make everything slided after some time, I thought that I have to break function in 2 parts: one accepts parameters and the second is called using javascript's setInterval.
So, here's the first one:
(function($){
$.fn.okwbSlider = function(params) {
//outer variables
var tgDfnr = this;
var somevar = this;
var MouseStatevar = 0;
var globalTimervar = (params.globalTimervar != undefined) ? params.globalTimervar : 4000;
var ActAsDefined = (params.ActAsDefined != undefined) ? params.ActAsDefined : "fadeItOut";
var SlidingTag = (params.SlidingTag != undefined) ? params.SlidingTag : 'img';
var numberOfChildren = tgDfnr.children(SlidingTag).length;
// alert('tgDfnr='+tgDfnr+' globalTimervar='+globalTimervar+' ActAsDefined='+ActAsDefined+' numberOfChildren='+numberOfChildren);
//alert("<"+tgDfnr.prop("tagName")+" id="+tgDfnr.attr('id')+">");
if (numberOfChildren > 1){
setInterval(function(){
okwbSlideIt(tgDfnr, ActAsDefined, numberOfChildren, MouseStatevar, SlidingTag);
}, globalTimervar);
}
if(numberOfChildren == 1){
tgDfnr.children(SlidingTag).fadeIn(500, function(){
$(this).addClass('active');
});
}
}
})(jQuery);
it contains everything that needed to run the function in jquery-like way (i.e. placing it after $('.yourANYClassNameOrId'))
and the second one (it's place higher in the text - re-accepts the entered parameters and works with them. It's written not in the really best way (I would write it much better now), but at least I think if you look at it, you can understand something useful.
So, let me know if you have questions and/or I can help you further.

Related

Animation example behaves erratically

I'm a beginner so I often use w3schools examples. They have the advantage of offering complete code, from html to /html. But this one failed.
I tried to use the example below to implement a game for young kids.
https://www.w3schools.com/js/tryit.asp?filename=tryjs_dom_animate_3
In my game, the user has to click on the correct location before the dropping object (a red square in this example) reaches the bottom.
Repeatedly clicking on the button produces erratic behaviour. At first the red square goes back up, but then sometimes it doesn't, and sometimes it reaches the bottom and bounces back up. If you click on it several times, quite fast, you will see what I mean.
I'm using Mozilla Firefox to test the game.
I think the problem comes from the fact that the code is interpreted in a non-linear fashion. I tried using while(1) with a break, I tried using global variables and testing each time before the move instruction as in :
if (finished == 1) return;
It's as if there was a thread somewhere who suddenly thought "Hey, I was moving this thing downwards. Let's send it up again halfway up the screen so I can finish bringing it down". And which does so even if "finish = 1".
I tried using timers as in :
setTimeout(function () {
if (finished == 1) return;
}, 100);
Nothing helped. I haven't tried to save the current state of the game in a bunch of cookies and to reload the page. Maybe I should do that, but isn't there a better way?
Here I made timer id global and clear it before starting again. In other words I stop the previous animation and start a new one.
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<p><button onclick="myMove()">Click Me</button></p>
<div id ="container">
<div id ="animate"></div>
</div>
<script>
var id = null;
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
</script>
</body>
</html>

Not cycling through img .src changes on 'click'

I have set up a piece of javascript that is meant to operate as a slideshow where you have to click right or left to go each way through an array of images. As it is, it only has 3 images and one button (the blue div) for going one way through the array.
I have scoured this code over and over and tried to separate the pieces of it but I could discern no pattern over what works. I have been stuck at this stage for months, and would therefore really appreciate some help.
<!DOCTYPE HTML>
<html>
<head>
<style>
#clicker { width: 200px; height:200px; background: blue; }
#pic { width: 300px; height: 150px; }
</style>
</head>
<body>
<div id="clicker"></div>
<img id="pic" src="models_web.jpg" alt="Icon" />
<script type="text/javascript">
var imgs = ["models_web.jpg","reflex_2.jpg","blue_web.jpg"];
var i = 0;
var addl = document.getELementById("clicker");
function clickrotate() {
document.getElementById("pic").src = imgs[i];
i++
if (i === 2) {i = 0};
}
addl.addEventListener( "click", clickrotate, false ) ;
</script>
</body>
</html>
You have a typo in your script.
var addl = document.getELementById("clicker");
change to var addl = document.getElementById("clicker");
Another thing, your counter increment is wrong. It will reset after viewing the second image, because you check i === 2 after incrementing it.
If you check the console in the developer tools in any modern browser, you will see what's wrong. It will save you the headaches next time.

Delay Gif until in viewport [duplicate]

I have a page with a lot of GIFs.
<img src="gif/1303552574110.1.gif" alt="" >
<img src="gif/1302919192204.gif" alt="" >
<img src="gif/1303642234740.gif" alt="" >
<img src="gif/1303822879528.gif" alt="" >
<img src="gif/1303825584512.gif" alt="" >
What I'm looking for
1 On page load => Animations for all gifs are stopped
2 On mouseover => Animations starts for that one gif
3 On mouseout => Animation stops again for that gif
I suppose this can be done in Jquery but I don't know how.
No, you can't control the animation of the images.
You would need two versions of each image, one that is animated, and one that's not. On hover you can easily change from one image to another.
Example:
$(function(){
$('img').each(function(e){
var src = $(e).attr('src');
$(e).hover(function(){
$(this).attr('src', src.replace('.gif', '_anim.gif'));
}, function(){
$(this).attr('src', src);
});
});
});
Update:
Time goes by, and possibilities change. As kritzikatzi pointed out, having two versions of the image is not the only option, you can apparently use a canvas element to create a copy of the first frame of the animation. Note that this doesn't work in all browsers, IE 8 for example doesn't support the canvas element.
I realise this answer is late, but I found a rather simple, elegant, and effective solution to this problem and felt it necessary to post it here.
However one thing I feel I need to make clear is that this doesn't start gif animation on mouseover, pause it on mouseout, and continue it when you mouseover it again. That, unfortunately, is impossible to do with gifs. (It is possible to do with a string of images displayed one after another to look like a gif, but taking apart every frame of your gifs and copying all those urls into a script would be time consuming)
What my solution does is make an image looks like it starts moving on mouseover. You make the first frame of your gif an image and put that image on the webpage then replace the image with the gif on mouseover and it looks like it starts moving. It resets on mouseout.
Just insert this script in the head section of your HTML:
$(document).ready(function()
{
$("#imgAnimate").hover(
function()
{
$(this).attr("src", "GIF URL HERE");
},
function()
{
$(this).attr("src", "STATIC IMAGE URL HERE");
});
});
And put this code in the img tag of the image you want to animate.
id="imgAnimate"
This will load the gif on mouseover, so it will seem like your image starts moving. (This is better than loading the gif onload because then the transition from static image to gif is choppy because the gif will start on a random frame)
for more than one image just recreate the script create a function:
<script type="text/javascript">
var staticGifSuffix = "-static.gif";
var gifSuffix = ".gif";
$(document).ready(function() {
$(".img-animate").each(function () {
$(this).hover(
function()
{
var originalSrc = $(this).attr("src");
$(this).attr("src", originalSrc.replace(staticGifSuffix, gifSuffix));
},
function()
{
var originalSrc = $(this).attr("src");
$(this).attr("src", originalSrc.replace(gifSuffix, staticGifSuffix));
}
);
});
});
</script>
</head>
<body>
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
<img class="img-animate" src="example-static.gif" >
</body>
That code block is a functioning web page (based on the information you have given me) that will display the static images and on hover, load and display the gif's. All you have to do is insert the url's for the static images.
I think the jQuery plugin freezeframe.js might come in handy for you. freezeframe.js is a jQuery Plugin To Automatically Pause GIFs And Restart Animating On Mouse Hover.
I guess you can easily adapt it to make it work on page load instead.
The best option is probably to have a still image which you replace the gif with when you want to stop it.
<img src="gif/1303552574110.1.gif" alt="" class="anim" >
<img src="gif/1302919192204.gif" alt="" class="anim" >
<img src="gif/1303642234740.gif" alt="" class="anim" >
<img src="gif/1303822879528.gif" alt="" class="anim" >
<img src="gif/1303825584512.gif" alt="" class="anim" >
$(window).load(function() {
$(".anim").src("stillimage.gif");
});
$(".anim").mouseover(function {
$(this).src("animatedimage.gif");
});
$(".anim").mouseout(function {
$(this).src("stillimage.gif");
});
You probably want to have two arrays containing paths to the still and animated gifs which you can assign to each image.
found a working solution here:
https://codepen.io/hoanghals/pen/dZrWLZ
JS here:
var gifElements = document.querySelectorAll('img.gif');
for(var e in gifElements) {
var element = gifElements[e];
if(element.nodeName == 'IMG') {
var supergif = new SuperGif({
gif: element,
progressbar_height: 0,
auto_play: false,
});
var controlElement = document.createElement("div");
controlElement.className = "gifcontrol loading g"+e;
supergif.load((function(controlElement) {
controlElement.className = "gifcontrol paused";
var playing = false;
controlElement.addEventListener("click", function(){
if(playing) {
this.pause();
playing = false;
controlElement.className = "gifcontrol paused";
} else {
this.play();
playing = true;
controlElement.className = "gifcontrol playing";
}
}.bind(this, controlElement));
}.bind(supergif))(controlElement));
var canvas = supergif.get_canvas();
controlElement.style.width = canvas.width+"px";
controlElement.style.height = canvas.height+"px";
controlElement.style.left = canvas.offsetLeft+"px";
var containerElement = canvas.parentNode;
containerElement.appendChild(controlElement);
}
}
Pure JS implementation https://jsfiddle.net/clayrabbit/k2ow48cy/
(based on canvas solution from https://codepen.io/hoanghals/pen/dZrWLZ)
[].forEach.call(document.querySelectorAll('.myimg'), function(elem) {
var img = new Image();
img.onload = function(event) {
elem.previousElementSibling.getContext('2d').drawImage(img, 0, 0);
};
img.src = elem.getAttribute('data-src');
elem.onmouseover = function(event) {
event.target.src = event.target.getAttribute('data-src');
};
elem.onmouseout = function(event) {
event.target.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
};
});
.mydiv{
width: 320px;
height: 240px;
position: relative;
}
.mycanvas, .myimg {
width: 100%;
height: 100%;
position: absolute;
}
<div class="mydiv">
<canvas class="mycanvas" width=320 height=240></canvas>
<img class="myimg" data-src="https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif">
</div>
You can solve this by having a long stripe that you show in steps, like a filmstrip. Then you can stop the film on any frame.
Example below (fiddle available at http://jsfiddle.net/HPXq4/9/):
the markup:
<div class="thumbnail-wrapper">
<img src="blah.jpg">
</div>
the css:
.thumbnail-wrapper{
width:190px;
height:100px;
overflow:hidden;
position:absolute;
}
.thumbnail-wrapper img{
position:relative;
top:0;
}
the js:
var gifTimer;
var currentGifId=null;
var step = 100; //height of a thumbnail
$('.thumbnail-wrapper img').hover(
function(){
currentGifId = $(this)
gifTimer = setInterval(playGif,500);
},
function(){
clearInterval(gifTimer);
currentGifId=null;
}
);
var playGif = function(){
var top = parseInt(currentGifId.css('top'))-step;
var max = currentGifId.height();
console.log(top,max)
if(max+top<=0){
console.log('reset')
top=0;
}
currentGifId.css('top',top);
}
obviously, this can be optimized much further, but I simplified this example for readability
A more elegant version of Mark Kramer's would be to do the following:
function animateImg(id, gifSrc){
var $el = $(id),
staticSrc = $el.attr('src');
$el.hover(
function(){
$(this).attr("src", gifSrc);
},
function(){
$(this).attr("src", staticSrc);
});
}
$(document).ready(function(){
animateImg('#id1', 'gif/gif1.gif');
animateImg('#id2', 'gif/gif2.gif');
});
Or even better would be to use data attributes:
$(document).ready(function(){
$('.animated-img').each(function(){
var $el = $(this),
staticSrc = $el.attr('src'),
gifSrc = $el.data('gifSrc');
$el.hover(
function(){
$(this).attr("src", gifSrc);
},
function(){
$(this).attr("src", staticSrc);
});
});
});
And the img el would look something like:
<img class="animated-img" src=".../img.jpg" data-gif-src=".../gif.gif" />
Note: This code is untested but should work fine.
For restarting the animation of a gif image, you can use the code:
$('#img_gif').attr('src','file.gif?' + Math.random());
Related answer, you can specify the number of playbacks on a gif. The below gif has 3 playbacks associated with it (10 second timer, 30 second playback total). After 30 seconds have passed since page load, it stops at "0:01".
Refresh the page to restart all 3 playbacks
You have to modify the gif itself. An easy tool is found here for modifying GIF playbacks https://ezgif.com/loop-count.
To see an example of a single-loop playback gif in action on a landing page, checkout this site using a single playback gif https://git-lfs.github.com/
This answer builds on that of Sourabh, who pointed out an HTML/CSS/JavaScript combo at https://codepen.io/hoanghals/pen/dZrWLZ that did the job. I tried this, and made a complete web page including the CSS and JavaScript, which I tried on my site. As CodePens have a habit of disappearing, I decided to show it here. I'm also showing a simplified stripped-to-essentials version, to demonstrate the minimum that one needs to do.
I must also note one thing. The code at the above link, whose JavaScript Sourabh copies, refers to a JavaScript constructor SuperGif() . I don't think Sourabh explained that, and neither does the CodePen. An easy search showed that it's defined in buzzfeed /
libgif-js , which can be downloaded from https://github.com/buzzfeed/libgif-js#readme . Look for the control that the red arrow below is pointing at, then click on the green "Code" button. (N.B. You won't see the red arrow: that's me showing you where to look.)
A menu will pop up offering various options including to download a zip file. Download it, and extract it into your HTML directory or a subdirectory thereof.
Next, I'm going to show the two pages that I made. The first is derived from the CodePen. The second is stripped to its essentials, and shows the minimum you need in order to use SuperGif.
So here's the complete HTML, CSS, and JavaScript for the first page. In the head of the HTML is a link to libgif.js , which is the file you need from the zip file. Then, the body of the HTML starts with some text about cat pictures, and follows it with a link to an animated cat GIF at https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif .
It then continues with some CSS. The CodePen uses SCSS, which for anyone who doesn't know, has to be preprocessed into CSS. I've done that, so what's in the code below is genuine CSS.
Finally, there's the JavaScript.
<html>
<head>
<script src="libgif-js-master/libgif.js"></script>
</head>
<body>
<div style="width: 600px; margin: auto; text-align: center; font-family: arial">
<p>
And so, the unwritten law of the internet, that any
experiment involving video/images must involve cats in
one way or another, reared its head again. When would
the internet's fascination with cats come to an end?
Never. The answer is "Never".
</p>
<img src='https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif' class='gif' />
</div>
<style>
img.gif {
visibility: hidden;
}
.jsgif {
position: relative;
}
.gifcontrol {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
cursor: pointer;
transition: background 0.25s ease-in-out;
z-index: 100;
}
.gifcontrol:after {
transition: background 0.25s ease-in-out;
position: absolute;
content: "";
display: block;
left: calc(50% - 25px);
top: calc(50% - 25px);
}
.gifcontrol.loading {
background: rgba(255, 255, 255, 0.75);
}
.gifcontrol.loading:after {
background: #FF9900;
width: 50px;
height: 50px;
border-radius: 50px;
}
.gifcontrol.playing {
/* Only show the 'stop' button on hover */
}
.gifcontrol.playing:after {
opacity: 0;
transition: opacity 0.25s ease-in-out;
border-left: 20px solid #FF9900;
border-right: 20px solid #FF9900;
width: 50px;
height: 50px;
box-sizing: border-box;
}
.gifcontrol.playing:hover:after {
opacity: 1;
}
.gifcontrol.paused {
background: rgba(255, 255, 255, 0.5);
}
.gifcontrol.paused:after {
width: 0;
height: 0;
border-style: solid;
border-width: 25px 0 25px 50px;
border-color: transparent transparent transparent #ff9900;
}
</style>
<script>
var gifElements = document.querySelectorAll('img.gif');
for(var e in gifElements) {
var element = gifElements[e];
if(element.nodeName == 'IMG') {
var supergif = new SuperGif({
gif: element,
progressbar_height: 0,
auto_play: false,
});
var controlElement = document.createElement("div");
controlElement.className = "gifcontrol loading g"+e;
supergif.load((function(controlElement) {
controlElement.className = "gifcontrol paused";
var playing = false;
controlElement.addEventListener("click", function(){
if(playing) {
this.pause();
playing = false;
controlElement.className = "gifcontrol paused";
} else {
this.play();
playing = true;
controlElement.className = "gifcontrol playing";
}
}.bind(this, controlElement));
}.bind(supergif))(controlElement));
var canvas = supergif.get_canvas();
controlElement.style.width = canvas.width+"px";
controlElement.style.height = canvas.height+"px";
controlElement.style.left = canvas.offsetLeft+"px";
var containerElement = canvas.parentNode;
containerElement.appendChild(controlElement);
}
}
</script>
</body>
</html>
When I put the page on my website and displayed it, the top looked like this:
And when I pressed the pink button, the page changed to this, and the GIF started animating. (The cat laps water falling from a tap.)
To end, here's the second, simple, page. Unlike the first, this doesn't have a fancy Play/Pause control that changes shape: it just has two buttons. The only thing the code does that isn't essential is to disable whichever button is not relevant, and to insert some space between the buttons.
<html>
<head>
<script src="libgif-js-master/libgif.js"></script>
</head>
<body>
<button type="button" onclick="play()"
id="play_button"
style="margin-right:9px;"
>
Play
</button>
<button type="button" onclick="pause()"
id="pause_button"
>
Pause
</button>
<img src="https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif"
id="gif"
/>
<script>
var gif_element = document.getElementById( "gif" );
var supergif = new SuperGif( {
gif: gif_element,
progressbar_height: 0,
auto_play: false
} );
supergif.load();
function play()
{
var play_button = document.getElementById( "play_button" );
play_button.disabled = true;
var pause_button = document.getElementById( "pause_button" );
pause_button.disabled = false;
supergif.play();
}
function pause()
{
var play_button = document.getElementById( "play_button" );
play_button.disabled = false;
var pause_button = document.getElementById( "pause_button" );
pause_button.disabled = true;
supergif.pause();
}
pause_button.disabled = true;
</script>
</body>
</html>
This, plus the example.html file in libgif-js, should be enough to get anyone started.
There is only one way from what I am aware.
Have 2 images, first a jpeg with first frame(or whatever you want) of the gif and the actual gif.
Load the page with the jpeg in place and on mouse over replace the jpeg with the gif. You can preload the gifs if you want or if they are of big size show a loading while the gif is loading and then replace the jpeg with it.
If you whant it to bi linear as in have the gif play on mouse over, stop it on mouse out and then resume play from the frame you stopped, then this cannot be done with javascript+gif combo.
Adding a suffix like this:
$('#img_gif').attr('src','file.gif?' + Math.random());
the browser is compelled to download a new image every time the user accesses the page. Moreover the client cache may be quickly filled.
Here follows the alternative solution I tested on Chrome 49 and Firefox 45.
In the css stylesheet set the display property as 'none', like this:
#img_gif{
display:'none';
}
Outside the '$(document).ready' statement insert:
$(window).load(function(){ $('#img_gif').show(); });
Every time the user accesses the page, the animation will be started after the complete load of all the elements. This is the only way I found to sincronize gif and html5 animations.
Please note that:
The gif animation will not restart after refreshing the page (like pressing "F5").
The "$(document).ready" statement doesn't produce the same effect of "$(window).load".
The property "visibility" doesn't produce the same effect of "display".
css filter can stop gif from playing in chrome
just add
filter: blur(0.001px);
to your img tag then gif freezed to load via chrome performance concern :)

jQuery: drag and drop folder slideshow for website

I'm creating a website for my organization that needs to have a slideshow for images. We do not often have quality access to internet, and the folks maintaining the site won't be highly knowledgeable in web design, so updating frequently is difficult. Therefor I am trying to generate an image slideshow that will pull images from a specific folder on the server.
http://www.codeproject.com/Tips/581747/jQuery-Slideshow-for-a-selected-folder?fid=1831110&select=4601478&fr=1
This appears to do just that, however I don't know fully what I'm doing. The guide says to place the HTML snippets in the head and body, that much is easy.
Next it states that a "simple sub" is to be created, and the following code is given...
Dim oDir As New DirectoryInfo(Server.MapPath("<relative path the images>"))
Dim fileList() As FileInfo = oDir.GetFiles("*.jpg")
Dim iFileCount As Integer = fileList.Count
iFileCount -= 1
Dim oImage As HtmlImage
For i As Integer = 0 To iFileCount
oImage = New HtmlImage
With oImage
.Src = String.Format("path\{0}", fileList(i))
If i = 0 Then .Attributes.Add("class", "active")
End With
slideshow.Controls.Add(oImage)
Next
I understand that "relative path the images" and "path" need to be updated with the name of the folder on my server... but I don't know what exactly to do with this code snippet. Does it get saved as a new .js file? I'm not seeing anything in the HTML that references another file.
Also... That guide uses a jquery API hosted on codeproject.com... I'm assuming its safe to sub it out for the same one hosted with google? I'd prefer not to rely on codeproject.com.
Steps to follow
1. Open your aspx/HTML page (your code sounds as if it's an aspx page)
2. With in the head/body paste the two javascript <script>...</script> tags codeproject has mentioned.
3. Do the same for the CSS which is within <style>...</style> tag
4. Drag and Drop an HTMLImage control to your webpage and name it slideshow
5. Your Sub needs to live on the page to populate the HTMLImage control with the images.
Important to check if your HTMLImage control is loaded with all the images. If you are using Chrome to test the website, hit F12 and look for your control under the tab called "elements". If the HTMLImage control contains all the server side images, the 1-3 steps mentioned above should be sufficient.
Hope that helps!
Please try the below mentioned code. Edit the tag at the bottom end of the code and add the link yo your image file within src="". This slideshow rotates every 7 due to accessibility reasons. You could change it to a different value in case you would like to do so. Please let me know if you are still having trouble fixing this!
`
<script src="http://code.jquery.com/jquery-1.10.2.min.js"
type="text/javascript"></script>
<script type="text/javascript">
/***
Simple jQuery Slideshow Script
Released by Jon Raasch (jonraasch.com) under FreeBSD license: free to use or modify,
not responsible for anything, etc. Please link out to me if you like it :)
***/
function slideSwitch() {
var $active = $('#slideshow IMG.active');
if ($active.length == 0)
$active = $('#slideshow IMG:last');
// use this to pull the images in the order they appear in the markup
var $next = $active.next().length ? $active.next() : $('#slideshow IMG:first');
// uncomment the 3 lines below to pull the images in random order
// var $sibs = $active.siblings();
// var rndNum = Math.floor(Math.random() * $sibs.length );
// var $next = $( $sibs[ rndNum ] );
$active.addClass('last-active');
$next.css({
opacity : 0.0
}).addClass('active').animate({
opacity : 1.0
}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
setInterval(function() {
console.log("fsdfsdf");
slideSwitch();
}, 7000);
});
</script>
<style type="text/css">
/*** set the width and height to match your images **/
#slideshow {
position: relative;
height: 350px;
width: 350px;
}
#slideshow IMG {
position: absolute;
top: 0;
left: 0;
z-index: 8;
opacity: 0.0;
height: 350px;
width: 350px;
}
#slideshow IMG.active {
z-index: 10;
opacity: 1.0;
}
#slideshow IMG.last-active {
z-index: 9;
}
</style>
</head>
<body>
<div id="slideshow">
<img src="http://www.tate.org.uk/art/images/work/D/D29/D29293_10.jpg" alt="Picture 1" class="active">
<img src="http://3.bp.blogspot.com/_ShpNcCZ0lVE/S_n3Xkv126I/AAAAAAAABbs/T0B8xwIg7Ko/s1600/IMG_7163.JPG" alt="Picture 2">
<img src="http://www.automotofoto.net/wp-content/uploads/2012/04/Honda-World-Superbike-Team-Heads-Home-for-Round-Three-THUMBNAIL-2.jpg" alt="Picture 3">
</div>
</body>
`

Jquery image cycling issues

I'm working on a website for a family friend. On it they wanted to have logos from all their associates on one row, that subtly fade to get replaced with additional logos that didn't fit the first time.
To achieve this i've assigned the <img>'s classes, that represent what cycle they should appear in, depending on how many of those images will fit on the row given its current width. This happens in my assignCycleNumbers function.
Then to actually fade them in and out i have another function called cycleAssociates which recursively fades the appropriate classes in and out. Well in theory, however it doesn't seem to be working properly, which is particularly odd because i tested the function here and it works fine. The only difference between them is that now i'm trying to assign the cycle numbers dynamically.
I'm really stumped and could do with some help!
You can see the website hosted here and if you scroll down to the bottom of the content you'll see the logos at the bottom, not behaving as expected. (First cycle appears okay but then subsequent cycles get muddled, more observable if you resize to a smaller screen width).
You can inspect the code thoroughly through your browser but here's everything you need to know, again i'd really appreciate any insight.
EDIT: The whole javascript file as requested. But all the relevant stuff is below:
JS:
//single global variable to represent how many logo cycles there is
var totalCycles = 0;
...
$(window).load(function() {
...
totalCycles = assignCycleNumbers();
cycleAssociates();
});
// window is resized
$(function(){
$(window).resize(function() {
...
totalCycles = assignCycleNumbers();
});
});
...
function cycleAssociates(){
var cycle = 0;
var recursiveCycling = function(cycle, totalCycles){
var currentAssociate = ".cycle" + cycle;
//fade in all img with the current cyle class over a second,
//wait 3 seconds before fading out over a second.
$(currentAssociate).delay(100).fadeIn(1000).delay(3000).fadeOut(1000,
function(){
cycle++;
if(cycle > totalCycles){
cycle = 0;
}
recursiveCycling(cycle, totalCycles);
});
};
recursiveCycling(cycle, totalCycles);
}
function assignCycleNumbers(){
//first remove any old cycle# classes (resized window case)
$('[class*="cycle"]').removeClass( function(unusedIdx,c){
return c.match(/cycle\d+/g).join(" ");
});
//measure div width
var divSpace = $("#bodies").innerWidth();
//assign a cycle number to a number of logos until no more will fit in that div
var cycleNum = 0;
$(".associate").each(function(){
if( divSpace - $(this).width() > 0){
$(this).addClass("cycle" + cycleNum);
divSpace = divSpace - $(this).width();
}
else{ //next logo won't fit current cycle, create next cycle
cycleNum++
$(this).addClass("cycle" + cycleNum);
divSpace = $("#bodies").innerWidth() - $(this).width();
}
});
return cycleNum;
}
html:
<img class="associate" src="IMG/spare.png" alt=""/>
<img class="associate" src="IMG/bcs_professional.jpg" alt="BCS Professional Member"/>
<img class="associate" src="IMG/climate_savers.jpg" alt="Climate Savers Smart Computing"/>
<img class="associate" src="IMG/code_of_conduct.jpg" alt="Data Centres Code Of Conduct Endorser"/>
<img class="associate" src="IMG/spare.gif" alt=""/>
<img class="associate" src="IMG/enistic.gif" alt="Enistic"/>
<img class="associate" src="IMG/greentrac_authorised.png" alt="Greentrac Authorised Reseller"/>
<img class="associate" src="IMG/very_pc.jpg" alt="Very PC Approved"/>
<img class="associate" src="IMG/spare.jpg" alt=""/>
css:
#bodies img.associate{
float: left;
max-width: 120px;
max-height: 80px;
display:none;
}
The issue is that your fadeOut function's callback is being executed even before all elements in the current cycle are faded out. Here's a modified version of your function that works as expected:
function cycleAssociates(){
var cycle = 0;
var recursiveCycling = function(cycle, totalCycles){
var currentAssociate = ".cycle" + cycle;
var n = $(currentAssociate).length; //How many images in current cycle?
$(currentAssociate).each(function() {
$(this).delay(100).fadeIn(1000).delay(3000).fadeOut(1000, function() {
n --;
if(n <= 0) { //current cycle done?
cycle++;
if(cycle > totalCycles){
cycle = 0;
}
recursiveCycling(cycle, totalCycles);
}
});
});
};
recursiveCycling(cycle, totalCycles);
}
To fix the issues that come up on window resize, try replacing your current $(window).resize handler with this:
$(function(){
$(window).resize(function() {
parallelNavbar();
$(".associate").stop(); //if there are any animations, stop 'em
$(".associate").hide(); //hide all associates
totalCycles = assignCycleNumbers(); //update the assignment
cycleAssociates(); //let's get cyclin' again!
});
});
Although I think you have some issues with scrolling. This should resolve the main cycling problem, though -- so I hope that helped!

Categories

Resources