Trigger function after background-image is loaded - javascript

I am using Jimdo and have a given div (containing 3 sub-divs, I think this is my general problem, but I am not sure) I found with the browser:
<div class="jtpl-background-area jqbga-container jqbga-web--image" background-area="" style="background-image: url('https://image.jimcdn.com/app/cms/image/transf/dimension=767x/path/s4354a59fbfee63e4/backgroundarea/ibb91266a7f033fa3/version/1529172695/image.jpg');background-position: 54.0833% 41.0025%;"></div>
How do I get a function triggered after the background-image of this is loaded?
I've already spent hours into this, tried tons of ways I found here or tools like waitforimages - still without success. What is going on with Jimdo / this div?
How do I get something triggered after the background-image is loaded?
var src = $('.jtpl-background-area').css('background-image');
var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');
var img = new Image();
img.onload = function() {
$('.jtpl-background-area').css('-webkit-animation', 'fadein 4s');
}
img.src = url;
if (img.complete) img.onload();
does not work.
$('.jtpl-background-area').waitForImages(true).done(function() {
$('.jtpl-background-area').css('-webkit-animation', 'fadein 4s');
});
does not work (waitforimages-script is included correct and opacity of .jtpl-background-area is set to 0 in css).
Any ideas?
$(window).on('load', function() {
$(".jtpl-background-area").css('-webkit-animation', 'fadein 4s');
});
causes backgrounds often popping up too late. Page is displayed while pictures are still not ready/fully loaded.
-
Edit:
Regarding Scott Marcus and the answer here by 'adeneo' (Wait for background images in CSS to be fully loaded):
$(window).on('load', function() {
$(".jtpl-background-area jqbga-container jqbga-web-
image").ready(function() {
$(".jtpl-background-area").velocity({ opacity: 1 },{ duration: 3000});
})
});
This here "works" - but my bg-images popping up too late.
But why does nothing happen if I exchange this with
var src = $(".jtpl-background-area jqbga-container jqbga-web-image");
var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');
var img = new Image();
img.onload = function() {
$('.jtpl-background-area').velocity({ opacity: 1 },{ duration: 3000});
}
img.src = url;
if (img.complete) img.onload();
?
Where is my mistake? Why doesnt this work and make my page stuck? It stays white and fails to load at all with this code.
Or in other words - how do I get
var src = $('#test').css('background-image');
var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');
var img = new Image();
img.onload = function() {
alert('image loaded');
}
img.src = url;
if (img.complete) img.onload();
to work with my (given and unchangeable)
<div class="jtpl-background-area jqbga-container jqbga-web--image" background-area="" style="background-image: url('https://image.jimcdn.com/app/cms/image/transf/dimension=767x/path/s4354a59fbfee63e4/backgroundarea/ibb91266a7f033fa3/version/1529172695/image.jpg');background-position: 54.0833% 41.0025%;"></div>
exactly?

Instead of using a background image, you can use an img element and CSS positioning to layer it behind the content of its parent div. Then, you can use the load event of the img element.
document.querySelector(".jtpl-background-area").addEventListener("load", function(){
console.log("Background loaded!");
$(".hidden").fadeIn(4000); // Fade the image in
});
/* by positioning the element absolutely and giving it a negative
z-index, we put it behind any other items in the same space. */
.jtpl-background-area { position:absolute; z-index:-1; top:0; left:0; }
div div { background-color:rgba(255,255,255, .5); }
.hidden { display:none; } /* Image will start off hidden */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>Some other div content</div>
<!-- The image will be hidden at first -->
<img class="hidden jtpl-background-area jqbga-container jqbga-web--image" background-area="" src="http://imgsrc.hubblesite.org/hvi/uploads/image_file/image_attachment/30741/STSCI-H-p1821a-m-1699x2000.png">
</div>

So here is what I came up with. We are basically creating an image, waiting for the file to load, then applying a style to the container.
Basically, we are making sure that no background-image is shown when the page loads by setting background:none !important; to the container.
We then create a new Image with JS, once that image's source is loaded, we apply a new class to the container, which sets the background image. You can add the animation and/or the opacity at your own discretion.
You may or may not have to fiddle around with the !important flag for your use case.
Is this what you had in mind?
$(document).ready(function() {
var img = new Image();
var container = $('.container');
img.src = "https://placeimg.com/640/480/any";
img.addEventListener('load', function() {
container.addClass('hasBackgroundImage')
});
});
.container {
opacity: 0;
background: none !important;
}
.hasBackgroundImage {
opacity: 1;
background-image: url('https://placeimg.com/640/480/any') !important;
background-size: cover;
height: 500px;
width: 500px;
transition: all ease-in-out 4s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>

You might do it like this:
Script starts working before the document has been loaded.
It intercepts the inline style of your div before it's been applied.
Then uses Image object to load the image and sets the background-image onload.
var i = setInterval(function() {
var div = document.querySelector('.jtpl-background-area');
if (div) {
clearInterval(i);
var src = div.style.backgroundImage.replace(/^url\(['"]?|['"]?\)/ig, '');
div.style.backgroundImage = 'none';
var img = new Image();
img.onload = function() {
div.style.backgroundImage = 'url(' + src + ')';
div.classList.add('loaded')
img = null;
}
img.src = src;
}
}, 10);
.jtpl-background-area {
width: 330px;
height: 200px;
opacity: 0;
}
.loaded {
transition: opacity 2s linear;
opacity: 1;
}
<div class="jtpl-background-area jqbga-container jqbga-web--image" background-area="" style="background-image: url('https://image.jimcdn.com/app/cms/image/transf/dimension=767x/path/s4354a59fbfee63e4/backgroundarea/ibb91266a7f033fa3/version/1529172695/image.jpg');background-position: 54.0833% 41.0025%;"></div>
Hope this helps.

Related

Jquery hover keep firing on a tag

The idea is that when users mouse over each name in the list, the div with id preview will have background image. The first a does not have a problem, but when I added the href, JavaScript keep firing the hover event. What is the problem here?
HTML
<ul>
<li><a>John</a></li>
<li>Sam</li>
<li>Tom</li>
</ul>
<div id="preview"></div>
JavaScript
jQuery(function() {
var names = $('a');
var bg = document.getElementById('preview');
names.hover(
changeBackground, handlerOut
);
function changeBackground(e) {
console.log('hover');
var image = 'http://londonalley.com/wp-content/uploads/2014/08/creativesUS3bb-1920x1080.jpg';
if (bg.style.cssText.length == 0) {
bg.style.cssText = builtStyle(image);
bg.style.display = "block";
}
}
function builtStyle(image) {
return "width: 100%;height: 100%;opacity: .6;position: absolute;top:0px;left: 0px;z-index: 101;opacity:.9: 1;display: block;visibility: visible;background-image: url(" +
image + ");"
}
//handle mouse leaves
function handlerOut() {
console.log('out');
if (bg.style.cssText) {
bg.style.cssText = "";
}
}
});
JSfiddle: https://jsfiddle.net/rattanak22/q96a6dz4/
Solution: Simply change your z-index css in the builtStyle function from 101 to -1
z-index: -1;
Note: You have specified opacity twice in your CSS.
The problem is you are setting background image as absolutely positioned without z-index. So when you hover over "a" tag, changeBackground function assigns an background image which is absolutely positioned with no z-index. That will bring image on top above all, like one more layer above "a" tag. As this new layer comes up, mouse cannot reach "a" tag which triggers hoverOut, and the cycle continues for every mouse moment.
function builtStyle(image) {
return "width: 100%;height: 100%;opacity: .6;position: absolute;top:0px;left: 0px;z-index: -1;opacity:.9: 1;display: block;visibility: visible;background-image: url(" +
image + ");"
}
https://jsfiddle.net/pradosh987/9p0pjtd4/
I have assigned -1 z-index to background image and that works.
After looking at your site, simply, change your css rules to:
#content-wrapper {
position: relative;
z-index: 102;
overflow: hidden;
}
#preview{
pointer-events: none;
}

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 :)

How to load an initial set of images, then animate between them randomly without jQuery

On my page I have a gallery (just a div) with several images on it. I want to show the first 9 images immediately, then load more images and use CSS transitions to animate between the existing images.
Loading the initial images is easy but I do not know the best way to load the next set of images and then start animating (using the CSS Transform property). So far this is what I have:
HTML (abbreviated):
<div id="mainContainer">
<div class="imageHolder"><img class="homeImages" src="test.png"></div>
<div class="imageHolder"><img class="homeImages" src="test1.png"></div>
<div class="imageHolder"><img class="homeImages" src="test3.png"></div>
</div>
CSS (abbreviated):
img {
display: inline;
position: relative;
margin: 0;
padding: 0;
width: 30%;
}
.changed.opaque {
opacity: 0;
border: 2px solid red;
}
I am looking to do a variety of effects, the most simple one would be to change the opacity and fade one image over the other. To load the next set of images I have this:
Javascript:
var imageArray = [
'test2.png',
'test3.png',
'test4.png',
'test5.png',
'test6.png',
];
var imageNodeArray = [];
for(var i = imageArray.length - 1; i >= 0; i -= 1) {
var img = new Image();
img.onload = function() {
imageNodeArray.push(this);
};
img.src = imageArray[i];
}
document.onclick = function() {
imageNodeArray[0].setAttribute('class', 'changed.opaque');
divs[0].appendChild(imageNodeArray[0])
}
This does add an image to my mainContainer however, even though I can tell from devTools that it has the changed.opaque class applied to it, no opacity is shown on the added image.
I am curious about this. I would also like to know the best way to "stack" images to have a bunch to animate through. I am not sure that appending child is right.... Thank you
function animate() {
var index = Math.floor((Math.random() * document.querySelectorAll('#mainContainer > .imageHolder').length + 1));
var current = document.querySelector('.top');
var next = document.querySelector('.imageHolder:nth-of-type(' + index + ')');
current.className = "imageHolder";
next.className += "top";
}
Should be able to handle and switch between any dynamically inserted images.
Currently using:
.imageHolder {
display: none;
}
.top {
display: inherit;
}
to switch the image is just a simple implementation.
Here's the working fiddle: http://jsfiddle.net/e9dxN/1/
Alternative implementation: http://jsfiddle.net/e9dxN/6/

toggleClass not removing initial div img source

I'm trying to toggle between images, but the code I have is just laying one on top of the other, not removing the initial image. This is what I have:
<script>
var button = document.getElementById('box'),
text = document.getElementById('menu');
button.onclick = function () {
var isHidden = text.style.display == 'none';
text.style.display = isHidden ? 'block' : 'none';
};
$("#box").click(function () {
$(this).toggleClass("red");
});
</script>
I have the intial image set up as a div and the second one as a class:
.close {
width: 29px;
z-index: 1;
height: 16px;
cursor: crosshair;
background-image: url('http://gabrielamagana.com/project1/ndxz-studio/site/sample/close-eye.png');
}
This is probably not the best way to set this up but '=I'm fairly new at this.
If you're trying to toggle images, try the following technique:
I don't have a clear understanding of your existing HTML structure so this simply serves as an example.
Live Demo
HTML
<div class='img1' id='dvImage'> </div>
JS
$(function(){
var ele = $('#dvImage');
ele.click(function(){
ele.toggleClass("img2");
});
});
CSS
.img1, .img2{
width:400px;
height:100px;
}
.img1{
background-image:url('http://dummyimage.com/400x150/000/fff');
}
.img2{
background-image:url('http://dummyimage.com/400x150/000/aaa');
}
NOTE: To get rid of the flicker between initial image loads, use a "sprite image." You'll gain performance by reducing requests and eliminate the flicker associated with loading new images.

Preload images during scroll

I am using Jquery to alter the source of an image as the page scrolls. However, currently they are loading as they are displayed and i would like to have them preload several images prior to being shown.
HTML
<img src="/img/1.jpg" />
JQuery
$(window).load(function(){
// Array of images to swap between
var images = [/img/1.jpg, /img/2.jpg, /img/3.jpg, /img/4.jpg];
var totalImages = images.length;
var documentHeight = $(document).height();
// Work out how often we should change image (i.e. how far we scroll between changes)
var scrollInterval = Math.floor(documentHeight / totalImages);
$(document).scroll(function () {
// Which one should we show at this scroll point?
i = Math.floor($(this).scrollTop() / scrollInterval);
// Show the corresponding image from the array
$('img').attr('src', images[i]);
});
});//]]>
css
img {
position: fixed;
top: 0;
left: 0;
height: 100%;
}
body {
height: 5000px;
}
Attempt.
I would like to add something similar to this to,
$(document).scroll(function () {
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
(new Image()).src = this;
});
}
i = Math.floor([i]+'1');
preload([[i]]);
}
But cannot figure how to code it... (New to JS)
Inside your loop.
var nextTenImages = images.slice(i, i+10);
// preload the next image
preload(nextTenImages);
JSFiddle: http://jsfiddle.net/gvee/ygkWH/8/
EDIT: Credit to the following SO topic for preloading images: Preloading images with jQuery

Categories

Resources