I used it and it worked perfect... and now I don't understand why it stopped working... I'm not a programmer so if I deleted something by mistake it's hars for me to find it... I did look everything... everything seems fine to me... please can you tell me why I now have UNDEFINED error ?
I have this in my heading :
<script type="text/javascript" src="js/textCycle.js"></script>
and this in my body tag :
<body onload="changeText()">
and this is where the script should be :
<table border = 0><tr><td style="width:300px;" height="100px"> <!-- Change the height in order to determine width of quotes -->
<div id="change"></div></td></tr></table>
and this is my JS :
var quotes=new Array(5);
var i = 0;
var authors=new Array(5);
//Load Quotes into array
quotes[0]="\"Temoignage #1\"";authors[0]="Client #1";
quotes[1]="\"Temoignage #2\"";authors[1]="Client #2";
quotes[2]="\"Temoignage #3\"";authors[2]="Client #3";
quotes[3]="\"Temoignage #4\"";authors[3]="Client #4";
quotes[4]="\"Temoignage #5\"";authors[4]="Client #5";
//Call the changeText() function every 5000 miliseconds
setInterval(changeText, 3000);
//Function that determine what quote and author to put in html.
function changeText(){
document.getElementById("change").innerHTML=(quotes[i] + '<p style="text-align: right"><i>' + authors[i] + '</i></p>');
if(i == 4)
i = 0;
else
i++;
}
I changed a few things in the JS and it was working... And suddently it stopped working after doing something (this is the something I can't remember!) and I'd like to know what is wrong with my code?
Thank you for your help!
It appears that there is another global i variable on your page, which is set to some arbitrarily high number bigger than the size of your quotes array, so it's undefined.
Rename i to something more descriptive like currentClientIndex and you should be good.
Related
I have a web app that outputs the results of a function as a double. The function compares two text documents and returns the percentage indicating the percentage of similarity between the two documents. When the user clicks a Compare button, the function runs and takes the user from the compare.jsp page to the results.jsp page, and displays a loading-bar that is filled in like so:
<div id="levenshtein-distance"
class="ldBar label-center levenshtein-distance"
data-preset="fan"
data-value="${result.percentage}"
data-stroke="">
</div>
This works fine, the fan bar gets the correct percentage. However, I am also trying to color the fan bar using the data-stroke value based on this percentage. I have a simple javascript function to do this, but can't figure out how to pass the value. I've tried running the function in the body tag of the results.jsp page using "onload", but this doesn't work. Here is my JavaScript function:
function barSetLD(percent) {
var red = "red";
var green = "green";
var orange = "orange";
var elem = document.getElementById("levenshtein-distance");
if (percent <= 40.00) {
elem.setAttribute("data-stroke", green);
} else if (percent > 40.00 && percent <= 70.00) {
elem.setAttribute("data-stroke", orange);
} else {
elem.setAttribute("data-stroke", red);
}
}
I've done quite a bit of searching and can't seem to find an example that helped me solve this. Any help is very much appreciated.
////Update:
Trinh, that worked to change the color, thanks! My problem now is that I do, in fact, have multiple 'levenshtein-distance' ids and I am looping through them. So currently everything is being set to the same color. I should have mentioned this initially, sorry. I am comparing multiple pairs of files and outputting the loading-bar for each pair. If you have some idea about how to resolve the looping issue, that would be great, but thanks for the original solution either way! I updated my javascript function as follows:
function barSetLD(percent) {
var red = "red";
var green = "green";
var orange = "orange";
var elem = document.querySelectorAll("[id^=levenshtein-distance]");
for (var i in elem) {
if (percent <= 40.00) {
elem[i].setAttribute("data-stroke", green);
} else if (percent > 40.00 && percent <= 70.00) {
elem[i].setAttribute("data-stroke", orange);
} else {
elem[i].setAttribute("data-stroke", red);
}
}
}
And the full bit of code with the html loop is, and I am now calling the barSetLD(percent) at the very bottom of the page as you suggested:
<c:forEach items="${studentResults}" var="result" varStatus="loop">
<div id="levenshtein-distance"
class="ldBar label-center levenshtein-distance"
data-preset="fan"
data-value="${result.percentage}">
</div>
</c:forEach>
<script type="text/javascript">
barSetLD("${result.percentage}");
</script>
Put your code at the very bottom of the page where all DOM has been loaded. Or at least make sure <div id="levenshtein-distance"/> exist and fully loaded before calling this document.getElementById("levenshtein-distance");. Also double check if you have multiple levenshtein-distance id...
Im trying to replace a news article every 5 minutes. I fetch the articles with pytho(flask) and then I render a template with multiple list of article title, article text, article image.
Now can get the title to switch every 5 minutes but for some reason the text won't change after the interval. It just does nothing. I tried so much, and I just can't figure out what is the problem.
Code:
var text = ["{{artikel_titel[0]}}", "{{artikel_titel[1]}}", "{{artikel_titel[2]}}"];
var counter = 0;
var elem = document.getElementById("titel");
var inst = setInterval(change, 5000);
function change() {
$("#titel").text(text[counter]);
counter++;
if (counter >= text.length) {
counter = 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=newsarticle_container>
<h1 id='titel'>{{artikel_titel}}</h1>
<img id=plaatje src="{{topimage}}">
<div id='tekst'>{{artikel_tekst}}</div>
</div>
So this one works for chaning the titles but as soon I use {{artikel_tekst[0]}} it just doesn't work. It looks like the text is too big to be updated. I also tried with elem.innnerHTML. (I haven't tried to replace the image yet).
Hopefully someone can help me out updating the article. I'm so confused why it's not working. If any questions,feel free to ask!
I have wrote this javascript to show some images with id: imgFotogramma1/imgFotogramma2/ecc.. randomly in 8 different div with id Fotogramma1/Fotogramma2/ecc..:
function rullino() {
var immagini = new Array("strutture/1.jpg", "strutture/2.jpg", "strutture/3.jpg", "strutture/4.jpg", "strutture/5.jpg", "strutture/6.jpg", "strutture/7.jpg", "strutture/8.jpg", "strutture/9.jpg");
for (i = 1; i < 9; i++) {
var x = Math.floor(immagini.length * Math.random(1));
var imgId = "imgFotogramma" + i;
$(function () {
$(imgId).fadeIn(1000);
src = $(imgId).attr('src');
src = immagini[x];
alert(src);
});
}
setInterval("rullino()", 4000);
};
Now,this code start when body is loaded and its repeated every 4 seconds but i don't understand why the images are not displayed. I have started to work with Jquery not too much time ago and probably something are wrong.
I want to specify that: if i use normally javascript to assign to the src attribute the value of immagini[x],all work fine and the images are displayed.I have problem only to apply the fadein() motion.
I need a help to understand where is wrong,i have studied the fadeIn() API and i have tried to apply to my case.
Thanks in advance to anyone want to help me.
$(imgId).fadeIn(1000);
should be:
$('#'+imgId).fadeIn(1000);
Use # + idOfElemnt to select element with particular id.
You already doing it right. Just replace
var imgId = "imgFotogramma"+i;
With
var imgId = "#imgFotogramma"+i;
Since your are using the ID of the image, then your must have to use the "#" for id for applying the jQuery on it.
To select an ID, use # + elemID. Like this:
var imgId = "#imgFotogramma" + i;
Also, fade will not occur if the element is not hidden. First hide it, and then fade it in:
$(imgId).hide().fadeIn(1000);
If OS is MAC I set a variable & then on condition I want to add new class in body tag.
Here is my code
<script type="text/javascript" language="javascript">
var mac=0;
if(navigator.userAgent.indexOf('Mac') > 0){
mac=1;
}else{
mac=0;
}
if(1==mac){
//document.body.className+='mac-os';
//document.getElementsByTagName('body')[0].className+='mac-os';
$('body').addClass('mac-os');
}else{
//document.body.className+='win-os';
//document.getElementsByTagName('body').className+='win-os';
//$('body').addClass('mac-os');
//$("body.className").addClass('win-os');
//document.body.className += " " + 'win-os';
$("body").addClass('win-os');
}
</script>
I have tried all but fail.
It's likely that the body element simply doesn't exist at the point your current code is being executed.
Ensure that your code is not executed until the DOM is ready, by putting it inside a ready handler:
$(document).ready(function() {
// your code
...
});
It would also work if you put it inside the <body> element, typically at the end of the page.
If your script is in head your should wait until the body to be loaded, Change your code to:
$(document).ready(function(){
var mac=0;
if(navigator.userAgent.indexOf('Mac') > 0){
mac=1;
}else{
mac=0;
}
if(1==mac){
//document.body.className+='mac-os';
//document.getElementsByTagName('body')[0].className+='mac-os';
$('body').addClass('mac-os');
}else{
//document.body.className+='win-os';
//document.getElementsByTagName('body').className+='win-os';
//$('body').addClass('mac-os');
//$("body.className").addClass('win-os');
//document.body.className += " " + 'win-os';
$("body").addClass('win-os');
}
});
Or put your script into body tag:
<body>
<!-- your script -->
<!-- others -->
</body>
The html elements don't exist until after the page loads, but your js is executing before the <body> tag is even read by the browser. Your script tags come before the <body> tag, so the browser executes the js code first. If you need to delay execution of your js code until after the page loads(as is the case with most js code)--and you don't want to use jquery--then you can do this:
<script type="text/javascript">
window.onload = function() {
//js code here
}
</script>
That function will not execute until the onload event occurs, which is after the page loads. The problem with the onload event is that all the images must load completely before the event fires, and that can take a long time, which will delay rendering any styles set by the js, or allowing buttons to fire onclick handlers set by the js.
As an alternative, you can put your script tags just before the closing body tag:
...
<script type="text/javascript">
//js code here
</script>
</body>
In that case, all the html on the page will have been parsed by the browser when the javascript tags are encountered, and as a result all the html elements will exist. <img> tags that are parsed will exist, but the browser doesn't wait for them to load--the browser continues on and parses the rest of the html while the images are loading. Even the body element exists even though its closing tag hasn't been seen yet.
Better still is to link to a js file, so that your js code isn't cluttering up the html:
<script type="text/javascript" src="myjs.js"></script>
</body>
Also, if you have this:
<body class="bgcolor">
...and your js code does this:
document.getElementsByTagName('body')[0].className += 'mac-os';
...then you will get his:
<body class="bgcolormac-os">
...which is not what you want. You need to add a space in there:
.... += ' mac-os';
...so that you get:
<body class="bgcolor mac-os">
A comment on your code style: you need to add more spaces, for instance:
if (1 == mac) {
document.getElementsByTagName('body')[0].className += 'mac-os';
}
else {
document.getElementsByTagName('body')[0].className += 'win-os';
}
Also, don't use 'cuddled' else clauses--they are really ugly. Consider using the style in the example where the else starts on a new line. Code clarity is what you are aiming for--not the fewest number of bytes. You might also consider indenting just 2 spaces--js statements can get pretty long, so conserving space there can be helpful.
And to avoid having to re-type those long document.get.... statements and make your code easier to read, you can do thing things like this:
var mybody = document.getElementsByTagName('body')[0];
if (1 == mac) {
mybody.className += ' mac-os';
}
else {
mybody.className += ' win-os';
}
Your code works, maybe you forgot to wrap your code with
$(function () {
//your code
});
?
$(function () {
var mac = 0;
if (navigator.userAgent.indexOf('Mac') > 0) {
mac = 1;
} else {
mac = 0;
}
if (1 == mac) {
//document.body.className+='mac-os';
//document.getElementsByTagName('body')[0].className+='mac-os';
$('body').addClass('mac-os');
} else {
//document.body.className+='win-os';
//document.getElementsByTagName('body').className+='win-os';
//$('body').addClass('mac-os');
//$("body.className").addClass('win-os');
//document.body.className += " " + 'win-os';
$("body").addClass('win-os');
}
});
Just put your jquery codes in $(document).ready(...) block to be sured that they execute in correct time...:
$(document).ready(function() {
// jquery codes...
$(document.body).addClass('your-class');
// ...
});
I am trying to create a simple image slideshow type thing with the Javascript code below, but what it is doing is displaying the first image in the webpage with everything else, then after 5 seconds clearing the page and displaying the same image, then again every 5 seconds except it doesn't clear the page anymore.
The JavaScript:
var waiPics=new Array();
waiPics[0]='images/path.jpg';
waiPics[1]='images/gorse.jpg';
waiPics[2]='images/stream.jpg';
waiPics[3]='images/pines.jpg';
waiPics[4]='images/stump.jpg';
var time;
function timeUp() {
delete document.write();
nextPic();
}
function nextPic() {
var picNum=0;
if (picNum = waiPics.length) {
picNum=0;
}
else {
picNum++;
}
document.write('<img src="'+waiPics[picNum]+'" title="Waipahihi" alt="Waipahihi">');
time=setTimeout("timeUp()",5000);
}
The HTML:
<script type="text/javascript">
<!-- Begin
nextPic();
// End -->
</script>
Im not very experienced with Javascript, so thanks in advance for the help.
picNum will always be zero because it is declared inside a function and will set to zero every time the function is called. Even if you fix this, your condition is wrong:
if (picNum = waiPics.length) {
The conditional should be:
if (picNum === waiPics.length) {
The single = sign assigns the length to picNum, then converts to a boolean. The array length is nonzero, so it becomes true value. It then resets to zero every time.
Consider using JSLint to check your code for errors and to suggest improvements. It flagged the issue:
"Expected a conditional expression and instead saw an assignment."
if (picNum = waiPics.length) {
In fact, after using JSLint on your code and examining its suggestions, I would use something more like this:
// New array creation syntax
var waiPics = ['images/path.jpg', 'images/gorse.jpg', 'images/stream.jpg', 'images/pines.jpg', 'images/stump.jpg'];
var picNum = 0; // Declare outside inner function so its value is preserved
var myDiv = document.getElementById("ssdiv"); // Get a div element to insert picture into
function nextPic() {
if (picNum === waiPics.length) { // Proper comparison
picNum = 0;
} else {
picNum += 1;
}
// Set picture into div element without evil document.write
myDiv.innerHTML = '<img src="' + waiPics[picNum] + '" title="Waipahihi" alt="Waipahihi">';
// No longer need timeUp; also don't use eval syntax
setTimeout(nextPic, 5000);
}
Assigning innerHTML avoids various problems with document.write and also does not require your page to refresh to change slideshow images. Also note other comments.
You need to use the comparison operator ('==') instead of assigning ('=') here:
//if (picNum = waiPics.length) {
if (picNum == waiPics.length) {
have a look at this example...
http://jsfiddle.net/DaveAlger/eNxuJ/1/
to get your own slideshow working, copy and paste the following html into any text file and save it as slides.html
you can add any number of <img> elements inside the <div class="slideshow">
enjoy!
<html>
<body>
<div class="slideshow">
<img src="http://davealger.info/i/1.jpg" />
<img src="http://davealger.info/i/2.bmp" />
<img src="http://davealger.info/i/3.png" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function(){
$('.slideshow img:gt(0)').hide();
setInterval(function(){$('.slideshow :first-child').fadeOut(2000).next('img').fadeIn(2000).end().appendTo('.slideshow');}, 4000);
});
</script>
<style>
.slideshow { position:relative; }
.slideshow img { position:absolute; left:0; top:0; }
</style>
</body>
</html>