CSS3 Slide Show Fade Effect not working - javascript

http://jsfiddle.net/pdb4kb1a/2/
The code works just fine on JSFiddle, but I cant get it to work when I use it in a HTML/CSS file. Only the 50x200 image is displayed, no signs of the simple slideshow or fade effect. I work in Sublime text, could that create any problems?
var imgArray = [
'http://placehold.it/300x200',
'http://placehold.it/200x100',
'http://placehold.it/400x300'],
curIndex = 0;
imgDuration = 3000;
function slideShow() {
document.getElementById('slider').className += "fadeOut";
setTimeout(function() {
document.getElementById('slider').src = imgArray[curIndex];
document.getElementById('slider').className = "";
},1000);
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout(slideShow, imgDuration);
}
slideShow();
#slider {
opacity:1;
transition: opacity 1s;
}
#slider.fadeOut {
opacity:0;
}
<body>
<img id="slider" src="http://placehold.it/50x200">
</body>

JSFiddle executes the javascript code in the window.onload event. You can change this if you click the JavaScript Button in the editor of JSFiddle.
If you change it to No wrap - in <head> you'll see that it doesn't work as well. You should see an error in your console, telling you the reason.
I'm assuming that you're including your script snippet in the head section of your HTML Document.
If you take your code as posted in your question, your slider isn't loaded yet, because the script is executed before your HTML document is fully loaded. You have to wrap the call to your slideShow function inside the onloadevent (or if you're using jQuery you'll probably use $(document).ready(function(){ ... }) instead.
This should do the trick then:
window.onload = function() {
slideShow();
}
Including the script at the bottom of your HTML document should work as well as an alternative.

Related

Vanilla javascript, not CSS or jQuery, fade in, fade out image change

I know this is fairly easy in jQuery, but I want to do this in plain 'ol "will be around forever" javascript.
I have a dropdown select on my page. I choose one of 8 options. There is a default image showing on the page. When I select an option, the image changes to that pic. It all works fine.
But I want to make the image change a fade out, fade in switch over because I, like most of you, can't leave well alone. We have to keep fiddling.
The javascript that I have, which is triggered by an onchange="setPicture()" on the select dropdown is:
function setPicture(){
var img = document.getElementById("mySelectTag");
var value = img.options[img.selectedIndex].value;
document.getElementById("myImageDiv").src = value;
}
This works fine. The value of the selected index is a string with the path for each image. I just want a fade out then fade in stuck in there somewhere. I have fiddled about a bit, calling another function before changing the src but no luck.
Can someone point me in the right direction?
The easier way would be to use css keyframes alone.
But from javascript there is the web animation api made for that.
Here is a quick modif from the example, to match your case.
function setPicture(){
alice.animate(
[
{ opacity: 1 },
{ opacity: .1},
{ opacity: 1 }
], {
duration: 3000,
iterations: Infinity
}
)
}
<button onclick="setPicture()">
OPACITY ANIMATION
</button>
<img id="alice"
src="https://mdn.mozillademos.org/files/13843/tumbling-alice_optimized.gif"
>
</img>
How about setting the image default CSS with the opacity of 0 and with transition time
then in JavaScript just add a class that will make the opacity set to 1
HTML:
<img class="img1" src="sampleimg.jpg">
CSS:
.img1 {
opacity: 0;
transition: all .3s;
}
.img1.show {
opacity: 1;
}
JS:
function setPicture() {
var img = document.querySelector('.img1');
img.src = 'urlofnewimage';
img.classList.add('show');
}
Hope this helps.
Juste one function for all :
function fadeOutEffect(target) {
var fadeTarget = document.getElementById(target);
fadeTarget.style.opacity = 1;
fadeTarget.style.transition = "opacity 2s";
fadeTarget.style.opacity = 0;
setTimeout(function(){
fadeTarget.style.display = "none";
}, 2000);;
}

Image slider hover stop and animated transition

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.

Fade In / Fade Out background images without white background

I want to create a website with background images that change over time with a fade in/fade out effect, but I don't want to use the existing jQuery fade in/fade out effect because with when one image faded out, a white background appeared before other image faded in. I found a plugin named Maximage that suits my request but it uses img tags while I want to work with background-image CSS (I have a good reason for doing this). Does anyone know how to do this?
Here's my HTML code:
<div id="wrapper">
//My contain here
</div>
Here's my JavaScript code so far:
//Auto change Background Image over time
$(window).load(function() {
var images = ['img/top/bg-1.jpg','img/top/bg-2.jpg','img/top/bg-3.jpg'];
var i = 0;
function changeBackground() {
$('#wrapper').fadeOut(500, function(){
$('#wrapper').css('background-image', function () {
if (i >= images.length) {
i = 0;
}
return 'url(' + images[i++] + ')';
});
$('#wrapper').fadeIn(500);
})
}
changeBackground();
setInterval(changeBackground, 3000);
});
Example: http://www.aaronvanderzwan.com/maximage/examples/basic.html
AHH ! Finally ! I found a nice technique ! I'm using a double wrapper.
The problem in your code is a bit logical. You can't fadeOut and fadeIn at the same time a single wrapper.
So the idea is to create two wrapper and to switch between them back and forth. We have one wrapper called: "wrapper_top" that encapsulate the second wrapper called: "wrapper_bottom". And the magic was to put beside the second wrapper: your content.
Thus having the structure ready which is the following:
<div id='wrapper_top'>
<div id='content'>YOUR CONTENT</div>
<div id='wrapper_bottom'></div>
</div>
Then a bit of JS+CSS and voilĂ  ! It will be dynamic with any amount of images !!!
Here is the implementation: http://jsbin.com/wisofeqetu/1/
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function() {
var i =0;
var images = ['image2.png','image3.png','image1.png'];
var image = $('#slideit');
//Initial Background image setup
image.css('background-image', 'url(image1.png)');
//Change image at regular intervals
setInterval(function(){
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + images [i++] +')');
image.fadeIn(1000);
});
if(i == images.length)
i = 0;
}, 5000);
});
</script>
</head>
<body>
<div id="slideit" style="width:700px;height:391px;">
</div>
</body>
</html>
If it doesn't have to be background-image, you can place all the images in your #wrapper, in <img>, it will work like a charm:
<div id="wrapper">
<img src="firstImage" class="imageClass"></img>
<img src="secoundImage" class="imageClass"></img>
<img src="thirdImage" class="imageClass"></img>
</div>
then some style. Every image has to be in same spot, so add position relative to #wrapper, and position absolute to .imageClass:
#wrapper{
position: relative;
}
.imageClass{
position: absolute;
top: 0;
left: 0;
display: none;
}
display: none; will hide every image.
Now some JQuery. To appear first image when window load write this:
$(window).load(function() {
$('.imageClass').eq(0).show();
});
by the .eq() "command" you can specify which one element with class '.imageClass' you want to use exactly. Starts with 0. After that just do something like that:
function changeBackground() {
var current = 0;
//tells which image is currently shown
if(current<$('.imageClass').length){
//loop that will show first image again after it will show the last one
$('.imageClass').eq(current).fadeOut(500);
current++;
$('.imageClass').eq(current).fadeIn(500);
} else {
$('.imageClass').eq(current).fadeOut(500);
current=0;
$('.imageClass').eq(current).fadeIn(500);
}
}
changeBackground();
setInterval(changeBackground, 3000);
});
That should work, hope you will like it.
You may also use jQuery plugin backstretch.

Showing/hiding <div> using javascript

For example I have a function called showcontainer. When I click on a button activating it, I want a certain div element, in this case <div id="container">, to fade in. And when I click it again, fade out.
How do I achieve this?
Note: I am not accustomed with jQuery.
So you got a bunch of jQuery answers. That's fine, I tend to use jQuery for this kind of stuff too. But doing that in plain JavaScript is not hard, it's just a lot more verbose:
var container = document.getElementById('container');
var btn = document.getElementById('showcontainer');
btn.onclick = function() {
// Fade out
if(container.style.display != 'none') {
var fade = setInterval(function(){
var opacity = parseFloat(container.style.opacity);
opacity = isNaN(opacity) ? 100 : parseInt(opacity * 100, 10);
opacity -= 5;
container.style.opacity = opacity/100;
if(opacity <= 0) {
clearInterval(fade);
container.style.opacity = 0;
container.style.display = 'none';
}
}, 50);
// Fade in
} else {
container.style.display = 'block';
container.style.opacity = 0;
var fade = setInterval(function(){
var opacity = parseFloat(container.style.opacity);
opacity = isNaN(opacity) ? 100 : parseInt(opacity * 100, 10);
opacity += 5;
container.style.opacity = opacity/100;
if(opacity >= 100) {
clearInterval(fade);
container.style.opacity = 1;
}
}, 50);
}
};
Check the working demo.
Provided you're not opposed to using jQuery per se, you can achieve this easily:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#showcontainer').click(function() {
$('#container').fadeToggle();
});
});
</script>
...
<div id="container">
...
</div>
...
<input type="button" id="showcontainer" value="Show/hide"/>
...
Note the missing http: in the beginning of the source of jQuery. With this trick the browser will automatically use http: or https: based on whether the original page is secure.
The piece of code after including jQuery assigns the handler to the button.
Best thing you could do is start now and get accustomed to jQuery.
The page http://api.jquery.com/fadeIn/ has all the example code that could be written here. Basically you want to have the call to fadeIn in your showcontainer function.
function showcontainer() {
$('#container').fadeIn();
}
You can have a look at jQuery UI Toggle.
The documentation turns the use of the library very simple, and they have many code examples.
You'd be as well off learning jQuery as it makes it a lot easier to do things!
From the sounds of it, you could have the container div already in the HTML but with a style of "display:none;", and then simply show it in your click event using (jQuery):
$('#container').fadeIn('slow', function() {
//Any additional logic after it's visible can go here
});

How do I fire an event when a iframe has finished loading in jQuery?

I have to load a PDF within a page.
Ideally I would like to have a loading animated gif which is replaced once the PDF has loaded.
Have you tried:
$("#iFrameId").on("load", function () {
// do something once the iframe is loaded
});
I'm pretty certain that it cannot be done.
Pretty much anything else than PDF works, even Flash. (Tested on Safari, Firefox 3, IE 7)
Too bad.
This did it for me (not pdf, but another "onload resistant" content):
<iframe id="frameid" src="page.aspx"></iframe>
<script language="javascript">
iframe = document.getElementById("frameid");
WaitForIFrame();
function WaitForIFrame() {
if (iframe.readyState != "complete") {
setTimeout("WaitForIFrame();", 200);
} else {
done();
}
}
function done() {
//some code after iframe has been loaded
}
</script>
Hope this helps.
I am trying this and seems to be working for me:
http://jsfiddle.net/aamir/BXe8C/
Bigger pdf file:
http://jsfiddle.net/aamir/BXe8C/1/
$("#iFrameId").ready(function (){
// do something once the iframe is loaded
});
have you tried .ready instead?
I tried an out of the box approach to this, I havent tested this for PDF content but it did work for normal HTML based content, heres how:
Step 1: Wrap your Iframe in a div wrapper
Step 2: Add a background image to your div wrapper:
.wrapperdiv{
background-image:url(img/loading.gif);
background-repeat:no-repeat;
background-position:center center; /*Can place your loader where ever you like */
}
Step 3: in ur iframe tag add ALLOWTRANSPARENCY="false"
The idea is to show the loading animation in the wrapper div till the iframe loads after it has loaded the iframe would cover the loading animation.
Give it a try.
Using both jquery Load and Ready neither seemed to really match when the iframe was TRULY ready.
I ended up doing something like this
$('#iframe').ready(function () {
$("#loader").fadeOut(2500, function (sender) {
$(sender).remove();
});
});
Where #loader is an absolutely positioned div over top the iframe with a spinner gif.
#Alex aw that's a bummer. What if in your iframe you had an html document that looked like:
<html>
<head>
<meta http-equiv="refresh" content="0;url=/pdfs/somepdf.pdf" />
</head>
<body>
</body>
</html>
Definitely a hack, but it might work for Firefox. Although I wonder if the load event would fire too soon in that case.
I had to show a loader while pdf in iFrame is loading so what i come up with:
loader({href:'loader.gif', onComplete: function(){
$('#pd').html('<iframe onLoad="loader.close();" src="pdf" width="720px" height="600px" >Please wait... your report is loading..</iframe>');
}
});
I'm showing a loader. Once I'm sure that customer can see my loader, i'm calling onCompllet loaders method that loads an iframe. Iframe has an "onLoad" event. Once PDF is loaded it triggers onloat event where i'm hiding the loader :)
The important part:
iFrame has "onLoad" event where you can do what you need (hide loaders etc.)
function frameLoaded(element) {
alert('LOADED');
};
<iframe src="https://google.com" title="W3Schools Free Online Web Tutorials" onload="frameLoaded(this)"></iframe>
Here is what I do for any action and it works in Firefox, IE, Opera, and Safari.
<script type="text/javascript">
$(document).ready(function(){
doMethod();
});
function actionIframe(iframe)
{
... do what ever ...
}
function doMethod()
{
var iFrames = document.getElementsByTagName('iframe');
// what ever action you want.
function iAction()
{
// Iterate through all iframes in the page.
for (var i = 0, j = iFrames.length; i < j; i++)
{
actionIframe(iFrames[i]);
}
}
// Check if browser is Safari or Opera.
if ($.browser.safari || $.browser.opera)
{
// Start timer when loaded.
$('iframe').load(function()
{
setTimeout(iAction, 0);
}
);
// Safari and Opera need something to force a load.
for (var i = 0, j = iFrames.length; i < j; i++)
{
var iSource = iFrames[i].src;
iFrames[i].src = '';
iFrames[i].src = iSource;
}
}
else
{
// For other good browsers.
$('iframe').load(function()
{
actionIframe(this);
}
);
}
}
</script>
If you can expect the browser's open/save interface to pop up for the user once the download is complete, then you can run this when you start the download:
$( document ).blur( function () {
// Your code here...
});
When the dialogue pops up on top of the page, the blur event will trigger.
Since after the pdf file is loaded, the iframe document will have a new DOM element <embed/>, so we can do the check like this:
window.onload = function () {
//creating an iframe element
var ifr = document.createElement('iframe');
document.body.appendChild(ifr);
// making the iframe fill the viewport
ifr.width = '100%';
ifr.height = window.innerHeight;
// continuously checking to see if the pdf file has been loaded
self.interval = setInterval(function () {
if (ifr && ifr.contentDocument && ifr.contentDocument.readyState === 'complete' && ifr.contentDocument.embeds && ifr.contentDocument.embeds.length > 0) {
clearInterval(self.interval);
console.log("loaded");
//You can do print here: ifr.contentWindow.print();
}
}, 100);
ifr.src = src;
}
The solution I have applied to this situation is to simply place an absolute loading image in the DOM, which will be covered by the iframe layer after the iframe is loaded.
The z-index of the iframe should be (loading's z-index + 1), or just higher.
For example:
.loading-image { position: absolute; z-index: 0; }
.iframe-element { position: relative; z-index: 1; }
Hope this helps if no javaScript solution did. I do think that CSS is best practice for these situations.
Best regards.

Categories

Resources