I'm having a bit of trouble getting my head around this thing so I thought it might help to post it here. So here it goes.
What I have: 5 different images in 5 different table cells + a script that I will post below.
What I want: to use the javascript's...
document.GetElementById("image ID").style.visibility='visible/hidden'
...after a preset time, but, instead of image ID there is a string that gets the ID of the image, and before anyone says anything, I am not using "" for the string that is inside of (). Something like...
var n=1;
function picID() {
pictureID="pic"+n;
n=n+1;
}
...and this way, every time that function is called we get the element ID of "pic1", "pic2", "pic3", etc.
What my problem is: the darn thing won't work. The image styling remains the same as I defined it in the img tag. (style="visibility:hidden")
All image ID's are within the img tag, as it should.
Here's the whole code:
<script>
var m=1;
function Show() {
if (m==6) {m=1;}
feat="feat"+m;
**document.getElementById(feat).style.visibility="visible";**
m=m+1;
setTimeout('Show()', 3000);
}
window.onload = Show;
</script>
<script>
var k=1;
function Hide() {
if (k==6) {k=1;}
feate="feat"+k;
**document.getElementById(feate).style.visibility="hidden";**
k=k+1;
setTimeout('Hide()', 3000);
}
window.onload = Hide;
</script>
I've separated the code so it'd easier to spot.
From what I've seen the only issue is the bold line within the code. I've tested everything else by replacing the document.getElementById with document.write, so I can see that the custom ID string thingy is working fine. It is. An everything else as well.
Any suggestions? Thanks.
Try setting k = 0; instead of k = 1;
It looks like when you load the page you have both the show() and the hide() functions running on the same element. Doing the above will make hide() run on the element BEFORE the element the show() runs on.
This code will keep on running in a loop.
because the setTimeOut() is called every time.
There should be a case when its not called
e.g if m<6 call it else don't
Related
I am using javascript/jQuery to manage a slide show that can handle random occurrences of portrait or landscape images.
The code works fine if there is an "alert" in the first function called to process a loaded image.
It fails without the alert.
I am testing locally and the images are loaded into an array when the page loads.
The files are quite small. I suspect however that the issue is one of timing.
Below is the function where the Alert works. I donĀ“t exactly understand what the code is doing as I am new to jQuery. It would help to know what the function is doing and a suggestion of how to fix the issue. I can post a working sample if it would help.
function FixImages(fLetterBox) {
$("div.aspectcorrect").each(function (index, div) {
var img = $(div).find("img").get(0);
alert("FixI")
FixImage(fLetterBox, div, img);
});
}
I suspect that you might be passing in the wrong arguments for the .each() callback. If you want div to refer to the element that is currently being looked at in each iteration, using $(this) should work:
function FixImages(fLetterBox) {
$("div.aspectcorrect").each(function (index) {
var img = $(this).find("img").get(0);
FixImage(fLetterBox, div, img);
});
}
I Have been trying to use this http://www.gloucesterwebdesign.com/showhidecontent/
but instead of hitting a link I want some JavaScript to call this function
like
if(input == true){
toggleLayer('id');
}
else if(input == false){
toggleLayer('id2');
}
the script call the toogleLayer function, but nothing happens, and curse
the input value is place within a other script there runs at page load up. I'm been wondering if this is the problem. anyone who like to comment on this?
-- Update --
So i was ask for more of the code,
http://pastebin.com/UD3tjz1s
The value in the localStorage is set on a other page, so you only get this page after that. this is only to show what kind of data im using
im a bit of a javaScript noob, so hope it's not to hard to read
Okay, I did a quick test and this will do it. Just replace your current function iwht this, it;s a lot cleaner and simpler. Also, document.getElementById(id) is supported in every current browser and goes back to IE6, so unless you want netscape support you don't; need all the extra code your resource provided.
function toggleLayer(id){
// get the element (this is supported in all modern browsers)
var element = document.getElementById(id);
// set the style display of this element to none if its set to be
// anything else than none, otherwise set it to block
element.style.display = element.style.display != "none"
? "none"
: "block";
}
I tested this and it worked.
Edit - [different thing!]
Okay, sorry I sort of misunderstood but I found a way to fix it. Heres what it comes down to: Because your javascript code is above your DIV elements, it gets executed BEFORE the DIV elements are created by the page. So javascript will look for the elements, and it will return undefined because, well, they aren't defined yet. SO you will have to either move your script to just before the ending tag, or add the following to the code (please not I also added an interval to see your function working):
window.onload = function(){
setInterval(setSize,1000);
// the rest of your functions here - the above interval is so you can see it toggling
}
// function toggleLater(){...} here
You might also want to move ToggleLayer OUTSIDE of the window.onload function, as you can't trigger it from the page otherwise (again, the function is now defined INSIDE window.onload and outside of the scope for DIV elements...).
I have this JavaScript (with jQuery):
var g_files_added, socket, cookie, database = null;
var file_contents = [];
function viewFile(key, filename) {
$('#title-filename').text(filename);
$('.prettyprint').text(file_contents[key]);
$('#viewFileModal').modal('show');
}
$(document).ready(function() {
$(document).on('shown', '#viewFileModal', function(event) {
prettyPrint();
});
});
// Variables have been set in code not shown, irrelevant to problem.
// prettyPrint() is called everytime the #viewFileModal is shown,
// but its effect is only felt once.
So prettyPrint() is invoked every time the viewFileModal modal box (courtesy of Bootstrap) is shown, it's just that it only seems to have an effect once per page load.
I have tried commenting out prettyPrint() and entering at the JS console after making the modal box appear. It indeed only has an effect the first time the box is shown (per page load).
Any ideas? I have been stuck on this a while. I also tried putting the call to prettyPrint() in the viewFile function; but the effect is the same.
Thanks a lot.
Sam.
Calling "prettyPrint()" adds a class to your PRE tags named "prettyPrinted" after it has been prettified. The line below will remove all instances of the "prettyPrinted" class on your page so that the prettyPrint() function can re-prettify you're PRE tags. This can be done without dynamically adding PRE tags to DIVs.
$('.prettyprinted').removeClass('prettyprinted');
Thanks to Matei. Solution was to change to be like this.
That is, add whole pre dynamically rather than just text.
var g_files_added, socket, cookie, database = null;
var file_contents = [];
function viewFile(key, filename) {
$('#title-filename').text(filename);
$('#fileblock').html('<pre class="prettyprint">' + file_contents[key] + '</pre>'); // fileblock is a div.
$('#viewFileModal').modal('show');
}
$(document).ready(function() {
$(document).on('shown', '#viewFileModal', function(event) {
prettyPrint();
});
});
:)
Joseph Poff answer is correct but you have to be careful. prettPrint() wraps everything in scan tags. If you remove the prettyprinted class, you aren't removing the scan tags. Unless you are clearing the contents of your pre (or stripping out all the scan tags), every time you recall prettyPrint() you will be adding scan tags, which will wrap your old scan tags. It can get out of control really quickly.
I am trying to a function to trigger once the body loads. I know that you can do this from the body tag, but I would prefer to do this from JS if this is possible.
For example: document.getElementsByTagName('body').onload = someFunc();
This does not work for me, but I think it shows what I essentially want to do.
EDIT:
I have tried the answers, what seems to be the issue is that it is calling the function before the elements it uses in the body tag are loaded, even if I put the script tags inside the body.
This is what it needs to do:
var buttonElements = document.getElementsByClassName('button');
And if I do:
alert(buttonElements)
It will pop up 0, but when I create a variable in the console, it will successfully populate it with the elements.
What you've got will almost work, but you have to import your JavaScript at the end of the <body> tag, and you have to index the first result:
document.getElementsByTagName('body')[0].onload = someFunc;
Like so:
window.onload = someFunc;
If however, your function accepts arguemnts, you would need anonymous function like this:
window.onload = function(){
someFunc(arg1, arg2);
}
BTW, other than fix that #Pointy mentioned for your code, you can also do:
document.body.onload = someFunc;
Dont use quotes... "someFunc"() won't work if you try to run it anyways.
window.onload = someFunc;
If you use jQuery:
$(document).ready(function () {
callMyFunction();
});
This might be a very basic question but I'm trying to understand this behavior
This is my javascript code. I want to know why second call to foo does not work. Here is the JSFiddle link
$.fn.foo = function(somestring){
var $this = this;
$this.html(somestring);
}
$(function(){
$('#container').foo("within function"); //this works
});
$('#container').foo("outside"); //this does not
The DOM is not fully loaded .. Thats the reason it won't work..
So when you encase your code inside the DOM Ready handler it waits for the document to be loaded and then runs the code inside.
This makes sure the element is available before any code is run on it..
When the HTML document is parsed , it parses top down.
So if the script is included in the head section , then the scripts are loaded first and then the HTML structure.. When you try to the run the code , it obviously won't work cause the element was still not parsed..
So encasing that in the handler will make sure the element is available before calling the methods on them..
This is because $('#container').foo("outside"); is evaluated before the body is processed. $('#container') will return with a length of 0. This is demonstrated below.
$.fn.foo = function(somestring){
var $this = this;
$this.html(somestring);
}
$(function(){
$('#container').foo("within function");
});
var element = $('#container');
console.log(element.length); //prints 0
element.foo("outside");
If the script is at the beginning of the page the rest of the HTML document has not been parsed yet, so the document looks empty to the script, so there is no #container yet.
$(function() { ... });
is (roughly) equivalent to
Wait till the whole HTML file is loaded and ready
Then execute function
so #container will be there and it will work. Another way to make it work would be to put the script below the rest of the page or at least below #container.