So in our school project we are creating an image gallery on web. I want to have three blocks with images, where all three blocks rotates between three images (a total of 9).
Like this [] [] [] where each block is an "image block", and in these three imageblocks the images will rotate between more images.
The thing is I found a code snippet which worked. The first answer.
Link: How to change image-background after sometime?
This code worked for one of my imageblocks. So I copyed the function and changed the function name, and it worked for two of them. Now I did exactly the same thing with the third, but then the image rotation stops on all three.
It says . Then it stops. If I remove one of the three "changeimage"s, it will work, and two will rotate, but when all three are there, none of them work.
Anyone wants to recreate my problem?
My HTML (Very short version, note that imglinks are not the real links, but a sample):
<body onload='changeimage(2); changeimage2(2); changeimage3(2);'>
<img id='myimage' src='imglink'/>
<img id='myimage2' src='imglink2'/>
<img id='myimage3' src='imglink3'/>
My javascript is exactly the same as in the link, except that I copyed and pasted it three times, and changed the name of the functions to what is in onload in the code snippet. I changed the myimage id, the function name in set time out and the image sources.
Everything works just fine. But when I use all three of them at the same time it wont work. Two of them will work together no matter which two, but all three wont work at the same time.
TLDR; wont work together, but two and one by themselves will.
Any suggestions? :) Ask if you didnt understand and I will try to explain even better.
The function you posted depends on an external variable "imageID". If you duplicated the function 3 times, then you need to duplicate the external variable too.
Example bellow:
<script type='text/javascript'>
var imageID=0;
function changeimage(every_seconds){
//change the image
if(!imageID){
document.getElementById("myimage").src="http://www.all-freeware.com/images/full/38943-nice_feathers_free_screensaver_desktop_screen_savers__nature.jpeg";
imageID++;
}
else{if(imageID==1){
document.getElementById("myimage2").src="http://www.hickerphoto.com/data/media/186/flower-bouquet-nice_12128.jpg";
imageID++;
}else{if(imageID==2){
document.getElementById("myimage3").src="http://www.photos.a-vsp.com/fotodb/14_green_cones.jpg";
imageID=0;
}}}
//call same function again for x of seconds
setTimeout("changeimage("+every_seconds+")",((every_seconds)*1000));
}
var imageID2=0;
function changeimage2(every_seconds){
//change the image
if(!imageID2){
document.getElementById("myimage").src="http://www.all-freeware.com/images/full/38943-nice_feathers_free_screensaver_desktop_screen_savers__nature.jpeg";
imageID2++;
}
else{if(imageID2==1){
document.getElementById("myimage2").src="http://www.hickerphoto.com/data/media/186/flower-bouquet-nice_12128.jpg";
imageID2++;
}else{if(imageID2==2){
document.getElementById("myimage3").src="http://www.photos.a-vsp.com/fotodb/14_green_cones.jpg";
imageID2=0;
}}}
//call same function again for x of seconds
setTimeout("changeimage("+every_seconds+")",((every_seconds)*1000));
}
var imageID3=0;
function changeimage3(every_seconds){
//change the image
if(!imageID3){
document.getElementById("myimage").src="http://www.all-freeware.com/images/full/38943-nice_feathers_free_screensaver_desktop_screen_savers__nature.jpeg";
imageID3++;
}
else{if(imageID3==1){
document.getElementById("myimage2").src="http://www.hickerphoto.com/data/media/186/flower-bouquet-nice_12128.jpg";
imageID3++;
}else{if(imageID3==2){
document.getElementById("myimage3").src="http://www.photos.a-vsp.com/fotodb/14_green_cones.jpg";
imageID3=0;
}}}
//call same function again for x of seconds
setTimeout("changeimage("+every_seconds+")",((every_seconds)*1000));
}
</script>
I am not so sure whether the problem is that onload can contain a list of functions to call or whether rather something in your script (which is missing here) is wrong. In any case, having a list of function in the onLoad seems not to be a good practice. I would write one dedicated function that handles onLoad and call those 3 functions from there.
So the html would look like this
<body onload='onLoadHandler()'>
<img id='myimage' src='imglink'/>
<img id='myimage2' src='imglink2'/>
<img id='myimage3' src='imglink3'/>
Your script would then look like this:
function onLoadHandler(){
changeimage(2);
changeimage2(2);
changeimage3(2);
}
// rest of your script
</script>
Further I would assume that having three changeimage functions is unessecary. They probably do three times almost the same just for different images. So in a next step I would reduce them to one single function, and pass the changing part as parameter to the function. Something like this.
<script type='text/javascript'>
function onLoadHandler(){
changeimage(2,'myimage');
changeimage(2,'myimage2');
changeimage(2,'myimage3');
}
function changeimage(numberParameter, imageId){
// your logic usining imageId instead of a fixed, hardcoded id
}
</script>
From looking at that code you've linked to, my immediate guess is that you haven't redeclared the imageID variable for each function to have its own, that could be causing issues.
However, I should note that redeclaring the function as you've described is the wrong way to go about this - the whole point of a function is that the code is reusable, and so you don't have to re-write it. As suggested by Daniel, using an additional parameter for the image DOM id is the best way to solve that problem.
I've re-written the function here with the logic improved slightly and allowed for re-use of the function:
http://jsfiddle.net/Ebp75/
Related
I have two Javascript files, both setup to generate an image from base64. The first script, called static.js looks like this.
var element = new Image();
element.src = "data:image/png;base64,..."
document.body.appendChild(element);
I can embed the script into my website using the following code and the image appears with no issues. (To see the full code, including the base64, go here)
<body>
<script src="./static.js"></script>
</body>
Similarly, I have a second script that I found on CodePen by takashi that converts a base64 image into an animated glitch. I was able to take that code and modify it using the same base64 image as the static code but with the glitch (apologies, but the code is really long even without my base64 image so I just included the link). The code for my image can be seen here. Note that while CodePen shows the HTML and Javascript on the same page, I broke mine out into separate files.
Again, if I embed the script into the webpage, it works with no issues.
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.7/p5.min.js"></script>
<script src="./glitch.js"></script>
</body>
The issue I have is that neither code has a dedicated javascript function() attribute, so the only way they work is if I embed the code as indicated above. Using the static image for brevity, if I add a dedicated function:
function isStatic() {
var element = new Image();
element.src = "data:image/png;base64,..."
document.body.appendChild(element);
}
and then try a callback,
<body>
<script src="./static.js">
isStatic();
</script>
</body>
the image does not appear on the webpage any longer. The same happens on the glitched image when I try to wrap the whole script into a function and then try a callback.
The main reason I was trying to turn each JS file into functions is so that I could combine the two into one file (which I did), and then using an embedded script like
<script>
setInterval(function(isStatic) {
// This will be executed every 9 seconds
}, 9000);
setInterval(function(isGlitch) {
// This will be executed every 2 seconds
}, 2000);
</script>
to create an image that switches from static to glitched, and then back again.
Since I was not able to successfully turn each JS file/script into it's own function, what I am trying to figure out is if there is a better way to combine my Static and Glitch JS scripts into one, or if there is a way that I can set the webpage to call each script file individually in such a way that creates a loop of the static and glitched images switching back and forth.
I have scoured the Google-webs looking for anything that describes what I am trying to do visually, but have absolutely nothing to show for it but a whole heap of scripts on various ways to make text and/or images glitch (just not how to make them start out static and then glitch randomly). Essentially what I would like to do with my two scripts is
- run static image (script or call) for *x* seconds (120-180 seconds)
- run glitched image (script or call) for *x* seconds (3-5 seconds)
- reset (loop) the sequence
in order to create the appearance of a single image that seems to randomly glitch for unknown reasons.
Edited answer after your clarifying comment:
Your code uses a library called p5, which is controlling your animation timing, so my previous answer is irrelevant. If you just want to change how often the glitch occurs, you already have almost everything you need. The glitch.js file already has a flag to turn the glitch on and off (this.throughFlag). And, it already has a slight random delay between glitches on line 226:
setTimeout(() => {
this.throughFlag = true;
}, floor(random(40, 400)));
The second parameter to setTimeout controls how long to wait beofre setting this.throughFlag to true (and thus starting to glitch again).
You just need to make this number longer. To do so, you want to make the time on the timeout longer, ie by multiplying it by some constant, which I'll call delayFactor.
const delayFactor = 10;
setTimeout(() => {
this.throughFlag = true;
}, delayFactor * floor(random(40, 400)));
See it in action here.
I have an image, and when the div it is inside is mousedover, I want a slideshow-type thing to start, where it fades to the first image, fades to the second image, fades to the third etc... and on mouseout it fades back to the original image.
I tried using the Cycle plugin with jQuery, but the site I'm using is hosting an incompatible version of jquery, and it is unfortunately uneditable. So, I tried to make my own, but there are so many problems.
HTML:
<div class="pro_feature" onmouseover="cyk()" onmouseout="norm()">
<div><img id="cykimg" src="sweet2.jpg" /></div>
<span>
<h2>Sweet</h2>
<p>lots of text</p>
View Products
</span>
</div><!-- end pro_feature -->
The JS:
function cyk(){
setTimeout(one1(),3000);
setTimeout(two2(),6000);
setTimeout(three3(),9000);
setTimeout(four4(),12000);
}
function one1(){
$("#cykimg").attr("src","/SXW-AOC-1D.jpg");
}
function two2(){
$("#cykimg").attr("src","/SXW-AOVB-1D.jpg");
}
function three3(){
$("#cykimg").attr("src","/SXW-CC-1D.jpg");
}
function four4(){
$("#cykimg").attr("src","/SXW-SCCS-1D.jpg");
}
function norm(){
$("#cykimg").attr("src","/sweet2.jpg");
}
The Problems:
It immediately goes to the last image, called by four4();
It does not fade
It does not cycle through
I've been searching for quite a long time for a solution, but I really haven't found anything that has gotten me remotely close (excluding Cycle, which I can't use). Any help or input is appreciated. I would be fine using jQuery if that is possible/easier.
You need to provide the function itself as a callback, and instead it is called when setting the timeout.
So instead of :
setTimeout(one1(),3000);
It should be
setTimeout(one1, 3000);
It looks like the functions aren't being called inside your setTimeout correctly. you can try something like:
setTimout(function () {
one1();
},1000);
Here's a fiddle with a small example that might help: http://jsfiddle.net/JeffreyTaylor/WTUA5/2/
I'm an jQuery noob and I'm wondering how fix this issue:
I have an external .js script, let's take reflection.js as example.
Reflection.js creates canvas reflection for every class="reflect" image.
I'm appending a few images trough different JS script that starts when ('document').ready.
Of course reflection.js doesn't work for images created by the script above.
How to avoid that?
I guess I'll need callback (?). Unfortunately I'm not getting idea of callbacks idea even after reading documentation.
[edit]
<script src="js/reflection.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery().ready(function() {
jQuery('#thumbs li').each(function(){
jQuery('.'+id+' a').append('<img src="' + imgURL + '" class="reflect" /></a>');
});
});
</script>
Image loading events do not bubble. You cannot hook into those.
Since your images have the class "reflect" it means you have some control over the source. So I recommend your reflection code publishes an API for you to call.
window.Reflect = function(img) {
...
};
...
var img = $("<img></img");
img.attr({
...
});
Reflect(img);
...
If you do not want to do this then you can poll the document for new images.
(function poll() {
var images = $("img.reflect");
...
images.removeClass("reflect")
setTimeout(poll, 500);
})();
If I understand this correctly, you have 2 functions under "ready" sequence and one script depends on other.
The way how I solved this problem, I have build my own includeJS as well as additional ready-checking layer on top of the one which jQuery has.
https://github.com/atk4/atk4/blob/master/templates/js/start-atk4.js
So my code looks like this:
$(function(){
$.atk4.includeJS('reflection.js');
$.atk4.includeJS('different.js');
$.atk4(function(){
$('.reflect').reflection();
});
});
What happens is, after document is ready, jQuery launches above code. It appends 2 scripts and evaluates them (by adding tag). When evaluation is complete, function atk4.get will execute readiness chain very similar to how jQuery does it.
I'm working on a client project and I have to include their header and footer, which includes some core JavaScript files. I have a couple of PNGs on the page, but their core JS file is poorly coded and doesn't check for IE 7 before attempting to replace IMG tags that contain .png files with DIVS that use the AlphaImageLoader filter. The result is that in IE 7, all my .png images are replaced with DIV tags that have a default display: block, causing a linebreak after every single png image in my pages.
What I'd like to do is override their function with a better one or somehow prevent theirs from executing, but I cannot modify the JS file itself, which both defines the function and attaches it to the window onload event. I've tried redefining the function under the same name in several places (header, just before the /body tag, in $(document).ready, etc...) but the original function always seems to execute, presumably because the original function code is what is stored with the event handler, and not merely a pointer to the function.
Any way I can fix? Is there a way to selectively remove onload event handlers?
If that's the only thing running at load, I think you could do
window.onload = null;
If there are other things running, I guess you'd have to reattach them. It's a little fragile, I suppose.
In IE7 you can use the detachEvent method:-
window.detachEvent("load", fn)
where fn is the function that was attached, however since there is jquery in this mix it may be a tall order getting hold of the actual function that was attached. Most likely the actual function attached will be anonymous.
A large IFRAME between header & footer should do the trick.
Well, depending on how it was bound, you might be able to get away with something like:
window.onload = function(){
var alert=function(a){
console.log(a);
}
window.onload();
}
Obviously, you'd want to redefine something other than alert, but that might work.
maybe if that's all it does, you can write a function to reverse it, look for all png images and strip away the div, and if you want to skip certain images you can implant an attribute to those you want to treat differently
another way is to trick the function by not having the png part of the image file name, and on load, append the .png (after their onload)
or maybe you can replace your png images with another tag, and replace onload
by the way, you can know exactly whats inside the onload, if you just alert window.onload, if there is nothing but that functionality, set window.onload = null;
Have you tried using $(window).unbind("load")?
Do you know the name of the function that replaces the PNG images? If so you might be able to override the existing function by doing something like this:
// Assuming PNG function is called pngSwap
function pngSwap() {
alert('png swap');
}
$(document).ready(function() {
if (window.pngSwap && window.pngSwap.constructor === Function) {
var oldFunc = window.pngSwap;
window.pngSwap = function() {
alert('new png swap');
}
}
pngSwap();
});
I'm trying to make Javascript change the style of certain DIV IDs by changing their background every few seconds. Basically, a fading header...here's my code, and it just doesn't change the background, at all.
How do you call a function?
http://pixolia.net/sandbox/morph/index.php
Your javascript is in functions and isn't being called from anywhere. Try calling one of the functions from window.onload, or $(document).ready(function(){ }); if you're using jQuery
you could do something like this
<body onload="Appear(id1, id2);">
that way when the page loads it starts the fadein/out
With the version I just saw up there, the onload call to Appear(id1, id2) is failing because id1 and id2 are not yet defined.
Either define id1 and id2, e.g
...
pics_array[2] = pic2;
var id1 = 0;
var id2 = 0;
but since its an onload function only getting called once, you may as well change the body tag to
The only problem then is the code falls over on this line:
new Effect.Appear('appear-div');
probably because the file effects.js can't be found.
sorry, ... change the boday tag to ... onload="Appear(0, 1);"