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);"
Related
I have a website running with Wordpress and using some extensions and plugins.
There is a button added through an extension, and I try to get this element with getElementById in javascript code added in the header of the page. But even inside a document.onload, the getElementById returns null.
I guess that's because the element is added dynamically after the page is loaded and even after the document.onload statment.
How could I manage to get the element in javascript?
Thanks for helping.
You might want to use a timer for this.
var myTimeInterval = setInterval(function() {
var el = document.getElementById("element");
if (el) {
// Your code here
clearInterval(myTimeInterval);
}
}, 1000);
This one will check every second whether #element exists or not, if it exists, perform your actions and remove the timer, if not, skip to the next iteration.
Try window.onload
http://javascript.tutorialhorizon.com/2016/03/17/window-onload-vs-document-onload/
A dirty solution may be to set a timeout before you try to select the element to give it time to load.
When I put this code:
window.onload = function(){
var inputs = document.querySelectorAll("input[type=text]");
console.log(inputs.length);
for(var j=0; j<inputs.length; j++){
inputs[j].onclick = function(){
this.style.width = "500px";
}
}
}
Into an html page, it works great, but if I put it into an external .js file the for loop never starts as inputs.length is equal to 0, even if in the page that calls the script there are plenty of inputs. What could be the problem?
Update:
I found out that the code works in normal conditions, but it doesn't:
on inputs that are contained in a div that was previously hidden and
then was shown via js my bad, the hidden input was of type "email"
on every input if they're loaded via ajax I found out why: since the function is fired only when the window loads, it won't see the loaded inputs
Very often, the placement of your script tag can affect your DOM selection. So make sure that your script tag is placed at the bottom of your html file just before the end of the body tag. Perhaps this will fix the issue!
Try attaching your function with addEventListener instead of setting window.onload:
window.addEventListener(function() {
//...
});
If this solves your problem then as #adeneo said, window.onload is being assigned elsewhere in the script which overwrites any other value it can have.
Which is why in general, using addEventListener is better as you can call it as many times as you want without overwriting anything.
But the problem could also simply be that your script isn't being evaluated at all, did you try putting some top-level console.log in there?
With the help of the users who commented/answered, I found out that some of the inputs I was trying the code to were of type "email" and not "text", while in other cases the inputs were loaded via ajax, so after the DOM was loaded. To fix these problems, I've edited
var inputs = document.querySelectorAll("input[type=text]");
To
var inputs = document.querySelectorAll("input[type=text],input[type=email]");
And I called again the function when the content loaded via ajax was ready.
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/
I have a question about javascript/html.
First, I have this:
var post = document.body.getElementsByClassName("post");
var x=post[i].getElementsByClassName("MyDiv")[0].innerHTML;
I get from the debugger that x is not defined, it doesn't exists.
This javascript function runs onload of the body. I am sure that I gave the right classnames in my javascript, so it should find my div.
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Is it possible that my function can't find the div with that classname because of this reason?
Is there a solution?
So, I read somewhere that sometimes javascript does not find an element because it is not yet there, it is not yet created in the browser ( whatever that means).
Browsers create the DOM progressively as they get the markup. When a script element is encountered, all processing of the markup stops (except where defer and async have an effect) while the script is run. If the script attempts to access an element that hasn't been created yet (probably because its markup hasn't been processed yet) then it won't be found.
This javascript function runs onload of the body.
If that means you are using something like:
<body onload="someFn()"...>
or perhaps
<script>
window.onload = function() {
someFn();
...
}
</script>
then when the function is called, all DOM nodes are available. Some, like images, may not be fully loaded, but their elements have been created.
If it means you have the script in the body and aren't using the load event, you should move the script to the bottom of the page (e.g. just before the closing body tag) and see if that fixes the issue.
Okay, instead of calling functions with
body onload, use jQuery's ready() function, or, if you don't want to use jQuery, you can use pure javascript, but this is up to you:
// jQuery
$(document).ready(function() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
});
// JavaScript
window.onload = function initialization() {
var post = document.getElementsByClassName("post"),
x = post[i].getElementsByClassName("MyDiv")[0].innerHTML;
}
A few side notes, I don't know what the use of innerHTML
is, and also if you're doing a for loop with i then definitely
post that code, that's kind of important.
After some discussion, my answer seems to have worked for you, but you can also place your script at the end of your body tag as #RobG has suggested.
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();
});