Need Assistance With JavaScript ImageSlider - What Am I Doing Wrong? - javascript

<script type="text/javascript">
var imageCounter = 1;
Function change() {
var image = doc.getElementById("image2");
if( imageCounter==1 ) {
image.src = '2.jpg';
imageNumber = 2;
}
else if( imageCounter==2 {
image.src = '3.jpg';
imageNumber = 3;
} else {
imageCounter = 1;
}
setInterval("change()",6500);
<button id="knapp1" type="button" onclick="change()">==></button>
Can anyone tell me what I am doing wrong? I have been trying to understand what I'm failing.

The main problem is that sometimes you assign to imageCounter and sometimes you assign to imageNumber. Decide on one name and use it consistently.
Also, function does not start with a capital letter. JavaScript is case-sensitive.

One problem is that you have
Function change()
with a capital F.
It should be function change()
another thing is that imageNumber is not declared. Im not sure what it is or what its used for but just do
var imageNumber;
setInterval("function()",6000);
It should not be in quotes.
setInterval(change(),6000);
Next thing, is that if you are running this off your computer, it will not find 3.jpg
Instead you have to give the complete file location of the image.
One last thing: on your function you are missing a curly bracket at the end.

heii
copy this code
<html>
<head>
<link rel="stylesheet" type="text/css" href="boss.css">
<script language="JavaScript">
var i = 0;
var path = new Array();
// LIST OF IMAGES
path[0] = "1.jpg";
path[1] = "2.jpg";
path[2] = "3.jpg";
function change()
{
document.slide.src = path[i];
if(i < path.length - 1) i++; else i = 0;
setTimeout("swapImage()",6500);
}
window.onload=change;
</script>
</head>
<body>
<center>
<img src="1.jpg" border="1" name="slide" height="300" width="750" id="image2"/>
</center>
<button id="knapp1" type="button" onclick="change()">==></button>
</body>
</html>

Related

.toLowerCase() not working among other things not working

JS
var score = 0
var yes = "yes"
var pokemonName = [];
var bg = [];
var index = 0;
document.getElementById('repete').style.visibility = 'hidden';
(function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
})();
function loop() {
var myAnswer = document.getElementById("myAnswer");
var answer = myAnswer.value;
if (answer.toLowerCase().trim() == pokemonName[num].toLowerCase().trim()) {
document.getElementById("text").innerHTML = "Correct, do you want to try again?";
score++
document.getElementById('repete').style.visibility = 'visible';
} else {
document.getElementById("text").innerHTML = "Incorrect, do you want to try again?" + "\n" + " The pokemon was " + pokemonName[num];
document.getElementById('repete').style.visibility = 'visible';
}
}
function loopRepete() {
var repete1 = document.getElementById("repete");
var replay = repete1.value;
if (replay.toLowerCase().trim() == yes.toLowerCase().trim()) {
asyncLoop();
} else {
document.getElementById("text").innerHTML = "Goodbye, your score is " + score;
location.href = 'index.html'
}
}
HTML
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Pokemon Quiz</title>
</head>
<body>
<lable> Answer </lable>
<input id="myAnswer" type="text">
<button onclick="loop()">click</button>
<p id="text"></p>
<div id="repete">
<lable> Answer </lable>
<input id="loop" type="text">
<button onclick="loopRepete()">click</button>
<p id="loopText"></p>
</div>
<script src="Gen3.js">
</script>
</body>
</html>
When I try take the input from the second second button (div id = repete) and put a toLowerCase() on it it does not work, and we I remove the toLowerCase() it still doesn't work but doesn't show a console error on the page. So I am confused On what I need to try do. I have tried to google it, but I could not find anything that helped.
You have to check if num exists in pokemonName array.
Otherwise, you'll be doing something like this:
[1,2,3][5].toLowerCase() which results in undefined.toLowerCase(), and you can't call .toLowerCase() on undefined as it only exists for String.
If you want asyncLoop to be defined you can't wrap it in a IIFE like that. I suspect you did that so it would run when the page loads, however there's another way to do that and still have the function defined for later use:
// define it like a normal function
function asyncLoop() {
background = bg[num = Math.floor(Math.random() * bg.length)];
document.body.style.backgroundImage = 'url(' + background + ')';
}
// and call it right away
asyncLoop();

Cannot read property 'setAttribute' of null - Javascript

I have seen a couple of questions posted with this error on here and having seen some of the answers I noticed the general consensus is that it is caused due to the DOM not being created yet. I have tried a few different solutions to fix it such as moving my script to immediately prior to the tag, using log outputs before and after the image creation in order to ensure the object is actually being created correctly but nothing has resolved my issue. I am new to Javascript so it might be something obvious I am missing?
var dice = [6, 6, 6, 6, 6];
function rollDice() {
for (var i = 0; i < dice.length; ++i) {
var num = Math.floor(Math.random() * 6 + 1);
dice[i] = 1;
document.write(dice[i] + "<br>");
}
for (var i = 0; i < dice.length; ++i) {
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value];
}
document.getElementById("dice_1").setAttribute("src", path)
}
<html>
<head>
<meta charset="utf-8">
<title>Project 1</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1> This is a javascript application</h1>
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<div>
<img id="dice_1" src="images/dice 1.png">
<img id="dice_2" src="images/dice 1.png">
<img id="dice_3" src="images/dice 1.png">
<img id="dice_4" src="images/dice 1.png">
<img id="dice_5" src="images/dice 1.png">
</div>
<input id="but" type="button" onclick="rollDice()" value="Roll Dice.">
<script>
console.log("script #1: %o", document.getElementById("dice_1")); // null
</script>
<script type="text/javascript" src="scripts/script.js"></script>
</body>
</html>
Since you're using document.write after the document has loaded, it's clearing the entire document (due to document.open() being called). Therefore, your img elements do not exist for setAttribute to be run against them. Try the following (note the index corrections that are needed due to array indexing starting at zero):
var dice = [6,6,6,6,6];
var results;
var resultsContainer = document.querySelector('.results');
function rollDice(){
// clear results array
results = [];
for(var i =0; i<dice.length; ++i){
var num = Math.floor(Math.random()*6 +1);
dice[i] = num;
results.push(dice[i]);
}
for(var i =0; i< dice.length; ++i){
var value = dice[i];
var path;
var ArrayImage = ["images/dice 1.png", "images/dice 2.png", "images/dice 3.png", "images/dice 4.png", "images/dice 5.png", "images/dice 6.png"];
path = ArrayImage[value - 1];
document.getElementById("dice_"+ (i + 1)).setAttribute("src",path);
}
// convert results array to text with <br> between them
var resultsStr = results.join("<br>");
// display results as text to page
resultsContainer.innerHTML = resultsStr;
}

how to make images link to different pages with javascript

What i want to do is to have each of the images that i m using link to a site when i click on them.The images keep changing with the setinterval() method and the function changeimage().I have some html and some javascript code:
HTML:
<!DOCTYPE html>
<html>
<head>
<link REL="STYLESHEET" TYPE="TEXT/CSS" HREF="STYLES.css">
<title>KURIA SELIDA</title>
<meta charset="utf-8">
</head>
<body>
<table class="tablearxikhs">
<tr>
<td></td>
<td class="tdarxikhs" STYLE="font-size:150%;"> ΚΑΤΑΧΩΡΗΣΕΙΣ </td>
<td class="tdarxikhs"><h1>ΤΑΞΙΔΙΩΤΙΚΟ ΓΡΑΦΕΙΟ </h1></td>
<td class="tdarxikhs" style="font-size:150%;">ΕΠΙΚΟΙΝΩΝΙΑ</td>
</tr>
</table>
<h2 style="text-align: center; ">Κορυφαίοι Προορισμοί Για το 2017-2018</h2>
<center><img id="myimages" src="kalabruta1.jpg" height="230" width="600"></center>
<br><br>
The JS part:
<br><br>
<script>
var image = document.getElementById("myimages");
var images = ["kalabruta1.jpg", "metewra1.jpg", "naxos11.gif", "metewra2.jpg", "kalabruta2.jpg", "naxos2.jpg"];
var i = 0;
function changeimage() {
if (++i >= images.length) i = 0;
image.src = images[i];
images[i].onclick = imglink;
}
setInterval(changeimage, 3000);
function imglink() {
window.location.href = 'https://www.google.gr/';
}
</script>
What i have tried in order to have the images link to a site doesnt work..Can somebody help?
I don't understand the logic of your code, however, this is my suggestion:
This line images[i].onclick = imglink; is using images[i] and that's incorrect because you're getting String objects, instead you need to replace that line with this: image.onclick = imglink; in order to apply the onclick event to the image.
<script>
var image = document.getElementById("myimages");
var images = ["kalabruta1.jpg", "metewra1.jpg", "naxos11.gif", "metewra2.jpg", "kalabruta2.jpg", "naxos2.jpg"];
var i = 0;
function changeimage() {
if (++i >= images.length) i = 0;
image.src = images[i];
image.onclick = imglink;
}
setInterval(changeimage, 3000);
function imglink() {
window.location.href = 'https://www.google.gr/';
}
</script>

how to do a printer-like text field using javascript OOP

I'm doing a printer-like text field which could show the letter one by one. I could realize it just use a function and load it as simple like:
html---
<div id="myTypingText"></div>
js---
<script>
var myString = "Place your string data here, and as much as you like.";
var myArray = myString.split("");
var loopTimer;
function frameLooper() {
if(myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += myArray.shift();
} else {
clearTimeout(loopTimer);
return false;
}
loopTimer = setTimeout('frameLooper()',70);
}
frameLooper();
</script>
But I want to do more advanced, I want to let the user to change the speed and change the text, so I wrote the following one but it went wrong, why? help me .thx.
html----
<div id="myTypingText"></div>
<p>Enter the tempo:</p><input type="text" id="tempo" value="70">
<p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn">
<button onclick="begin()">Begin</button>
js----
<script type="text/javascript">
function Printer(){
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.len = this.myArray.length;
this.loop = function (){
if(this.len > 0 ){
document.getElementById("myTypingText").innerHTML += this.myArray.shift();
}
}
}
function begin(){
var test = new Printer();
setInterval(test.loop,test.tempo);
}
</script>
You need to use an anonymous function in the interval if you want the loop function to be executed in the context of the Printer object. Also you need to check the length of the array each time as the len property won't be updated when the array is shifted.
function Printer() {
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.loop = function () {
if (this.myArray.length > 0) {
document.getElementById("myTypingText").innerHTML += this.myArray.shift();
}
}
}
function begin() {
var test = new Printer();
setInterval(function () {
test.loop()
}, test.tempo);
}
See the working fiddle
Here's another approach. Your fundamental problem was with using the this keyword. You have to remember that when you enter another function scope, the this keyword changes. You'll notice here that I cache or save 'this' to equal that, then use that new 'that' value in the function. Plunker
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="myTypingText"></div>
<p>Enter the tempo:</p><input type="text" id="tempo" value="70">
<p>Enter the Text:<p><input type="text" id="text" value="abcdefghijklmn">
<button onclick="begin()">Begin</button>
<script type="text/javascript">
function Printer(){
this.myString = document.getElementById("text").value;
this.myArray = this.myString.split("");
this.tempo = document.getElementById("tempo").value;
this.len = this.myArray.length;
var that = this;
this.loop = function (){
if(that.myArray.length !== 0 ){
document.getElementById("myTypingText").innerHTML += that.myArray.shift();
}
}
}
function begin(){
var test = new Printer();
setInterval(test.loop,test.tempo);
}
</script>
</body>
</html>

Using a Regex to insert a / at the end of an img tag

I want to insert an ending slash before the closing bracket of every img tag found in a string.
This (modified from here) is correctly returning the position of each instance of img:
var re = /img\s/g,
match;
while (match = re.exec(str)) {
console.log(match.index); //
}
Knowing this, how can I find the next > after each imgand insert a / before it?
How about this, it's simple but seems like it would work for your case:
str.replace(/(<img[^>]*)>/g, "$1 />");
if you wanted it to be a little more smart, you could do something like this:
str.replace(/(<img[^>]*?) *\/?>/g, "$1 />");
this would account for things that already have a space and/or a slash at the end... and create the same output for all of the following:
IN:
<img src='foo.png'>
<img src='foo.png' >
<img src='foo.png'/>
<img src='foo.png' />
OUT for all the above:
<img src='foo.png' />
if you would rather have <img src='foo.png'/>, just remove the space after $1 in the replace.
try something like this:
var imgs = "<img blblblb > <img adadasd>"
var pattern = /(<img[^>]*)>/g;
imgs = imgs.replace(pattern, "$1/>");
console.log(imgs);
//<img blblblb /> <img adadasd/>
I have a non-regex solution, if you’re interested:
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1"/>
<script type="text/javascript">
function close_img_tags(){
var str = document.getElementById("txt").value, len = str.length, i, j;
for(i = 0; i < len-4; i++){
if(str[i]+str[i+1]+str[i+2]+str[i+3] == "<img"){
for(j = i+4; j < len; j++){
if(str[j] == ">"){
if(str[j-1] != "/"){
str = str.substr(0, j)+"/"+str.substr(j);
i = j+2;
}
else{
i = j+1;
}
break;
}
}
}
}
document.getElementById("txt").value = str;
}
</script>
<style type="text/css">
textarea{
width:400px;
height:300px;
}
</style>
</head>
<body>
<textarea id="txt"></textarea><br/>
<button type="button" onclick="close_img_tags();">Edit HTML</button>
</body>
</html>
Demo: http://jsfiddle.net/eZu9U/

Categories