Simple Javascript Gallery - javascript

So I'm trying to loop through this array and change an image source every few seconds. Right now I have an onload event calling a setTimeOut method which should change the image 5 seconds after the page has loaded I would think, but it is doing it instantly. What is the problem? Here is my code:
<html>
<head>
<title>Ad Rotaror</title>
<script type="text/javascript">
var i = 0;
var ads = new Array(4);
ads[0]='promo1.gif';
ads[1]='promo2.gif';
ads[2]='promo3.gif';
ads[3]='promo4.gif';
ads[4]='promo5.gif';
function change()
{
if(i > 4)
i = 0;
document.images[0].src = ads[i];
i++;
}
</script>
</head>
<body>
<img src="promo1.gif" onload="setInterval(change(), 5000)" />
</body>
</html>

Change 'change()' to 'change'. You are calling the function immediately.

Related

How to call a function in external script file from HTML

I'm trying to call a javascript function in my HTML index file and I can't get it to work.
This is my html file that I'm trying to call a function from.
<div class="main">
<h1 class="header-main" onload="HeaderTyper('Welcome', this)">
<noscript>no javascript</noscript>
</h1>
</div>
<script type="text/javascript" src="script.js"></script>
And this is the script.
function HeaderTyper(message, element){
var i = 0;
var speed = 50;
if (i < message.length) {
element.innerHTML += message.charAt(i);
//play keystroke sound
i++;
setTimeout(HeaderTyper, speed);
}
}
I'm trying to get a typewriter effect style header. I'm planning to add some keystroke sounds, but first I need to figure out how to actually type it out in the header tag. The code won't type out the message I'm passing in argument. What did I do wrong ? Thank you for any help.
After the HTML page ends (As #johannchopin explained), import the file and then add an event listener (as #aaronburrows explained).
<body>
<div class="main">
<h1 class="header-main">
<noscript>no javascript</noscript>
</h1>
</div>
</body>
</html>
<script type="text/javascript" src="script.js"></script>
<script>
let h1 = document.querySelector('.header-main');
h1.addEventListener('load', HeaderTyper("Welcome", h1, false));
</script>
Also, I fixed the function, it was missing the parameters.
function HeaderTyper(message, element, i) {
var speed = 50;
if (i < message.length) {
console.log(message.charAt(i))
element.innerHTML += message.charAt(i);
//play keystroke sound
setTimeout(function(){ HeaderTyper(message,element,++i)}, speed);
}
}
You're attempting to bind a function call before it is loaded into the browser. Remove the onload from the HTML and add an event listener to the script.
According to this solution, The onload event can only be used on the document(body) itself. Best way to achieve this is to call the function in a <script> tag just before the </body> closing tag:
<div class="main">
<h1 class="header-main">
<noscript>no javascript</noscript>
</h1>
</div>
<script>
function HeaderTyper(message) {
var i = 0;
var speed = 50;
var element = document.querySelector('.header-main');
if (i < message.length) {
element.innerHTML += message.charAt(i);
//play keystroke sound
i++;
setTimeout(HeaderTyper, speed);
}
}
HeaderTyper('Welcome');
</script>
Ok, hi there.
function HeaderTyper(message, element){
alert('script loaded') //<---
var i = 0;
I put this line at the beginning of the script to make sure it works. And it's not.
Why?
Because you just made your function but doesn't call it.
First way to solve this - put ur function in the "script" of HTML doc. And call it after, like
<script>
function HeaderTyper(message) {
let i = 0
let speed = 50
let element = document.querySelector('.header-main')
if (i < message.length) {
element.innerHTML += message.charAt(i)
i += 1
setTimeout(HeaderTyper, speed)
}
}
HeaderTyper('Welcome') //<---
</script>
Second way - put HeaderTyper() at the end of script.js file, so the function start, but you need to make a link for "message" and "element".
setTimeout(HeaderTyper, speed);
}
}
HeaderTyper(someMessage, someElement) //<---

Javascript if statements in displaying images

Hey i am currently trying to get a program running in javascript i want the program to display the 4 images one after each other with the single press of a button and then after the 4 images have cycled through i want them to stop cycling and i cant seem to do it this is my code i currently have:
<html>
<head>
<script>
var images = ["image1.png","image2.png","image3.png","image4.png"];
var imagenum = 0;
var timer;
function imageCycle()
{
if(++imagenum == 4)
imagenum = 0;
document.image.src = images[imagenum];
timer = setTimeout("imageCycle()",1000);
}
</script>
</head>
<body>
<img src="image1.png" name="image" width=800 height=600>
<form>
<input type="button" value="images" name="cycle images" onclick="imageCycle()">
</form>
</body>
</html>
any help is appreciated many thanks!
In your code you continue to schedule the function, that's why the images continue to rotate.
If you want to stop at the forth image displayed, you have to put the setTimeout line in an else statement.
if (++imagenum == 4) {
imagenum = 0;
} else {
document.image.src = images[imagenum];
timer = setTimeout("imageCycle()",1000);
}
Another point, that other users notice and I just report here in my answer.
You use the string:
imageCycle()
as the first argument of setTimeout, insted you should use just the function name.
timer = setTimeout(imageCycle, 1000);

Cordova SQLite plugin only works on first call

I have a cordova app with two pages, the first has a search field and the second displays the results of the first.
The displayResults function
function displayResults(){
var query = localStorage.getItem('search');
var db = window.sqlitePlugin.openDatabase({name:"Store-DB", location: 1});
queryDB(db,query);
}
function queryDB(db,query){
db.transaction(function(tx) {
var queryList = query.split(" ");
var sqlText = "SELECT * FROM DB WHERE item LIKE '%"+queryList[0]+"%'";
for (i = 1; i < queryList.length; i++) {
sqlText += " OR item LIKE '%"+queryList[i]+"%'";
}
tx.executeSql(sqlText, [], querySuccess);
}
);
}
function querySuccess(tx,results) {
var i;
var len = results.rows.length;
//Iterate through the results
for (i = 0; i < len; i++) {
console.log(row);
//Get the current row
var row = results.rows.item(i);
var div = document.createElement("div");
div.style.background = "gray";
div.style.color = "white";
div.innerHTML = row;
document.body.appendChild(div);
}
alert("Finished");
}
Here is the code for the second page:
<link rel="stylesheet" type="text/css" href="css/default.css">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/zepto.js" type="text/javascript"></script>
<script src="plugins/com.brodysoft.sqlitePlugin/www/SQLitePlugin.js" type="text/javascript"></script>
<script src="js/code.js" type="text/javascript"></script>
<script type="text/javascript">
function onLoad(){
document.addEventListener("deviceready", onDeviceReady(), false);
}
function onDeviceReady(){
displayResults();
}
</script>
</head>
<body onload="onLoad()">
<div id="taskbar">
Home
<a id="username" class="toolbar_item" style="float:right;" href="#"></a>
</div>
The first time you load this page displayResults works just fine, but if you click the link back to the main page and load the second page again the console prints the error ReferenceError: no "undefined" has no property "openDatabase" in other words, the SQLite plugin isn't loading. But, if I make displayResults fire on a button press instead of onload it works every time. What is the explanation for this peculiar behavior?
It seems that sometimes deviceready-event is either not fired at all or fired too early when there are more event handlers of different libraries in place. The second problem caused that the brodysoft-plugin is not loaded properly and assign to the window-object as window.sqlitePlugin property because one event handler dispatched deviceready-event too early. It turned out setTimeout was the answer as it had been here
You can use the onpageshow event for example
$('#idofyourpage').bind("onpageshow",function(){
//Do something
});

Image changing loop not working

I have written a JavaScript that is supposed to change my header image every three seconds. For some reason nothing happens when I'm opening my page.
Can anyone see what I'm doing wrong?
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="changeImage.js"></script>
<title>Mikael Mattsson</title>
</head>
<body>
<div class="header">
<img id="headerImg" src="images/header-image.png" alt="Header image" width="100%" hight="100%">
</div>
</body>
</html>
JavaScript:
var images = [];
images[0] = "images/header-image.png";
images[1] = "images/header-image2.png";
var x = 0;
function imageChanger(){
var img = document.getElementById("headerImg");
img.src = images[x];
x++;
if (x > images.length){
x = 0;
}
setTimeout("imageChanger()", 3000);
}
x > images.length should be x >= images.length.
setTimeout("imageChanger()", 3000); must be changed to setTimeout(imageChanger, 3000);
You call the setTimeout inside the function but never call the function. So the timeout is never set, hence the function is not called through the timeout.
I recommend using setInterval above setTimeout in your case since you want to have the function executed repeatedly. Also you could improve the way you increase x.
var x = 0;
function imageChanger() {
var img = document.getElementById("headerImg");
x = (x + 1) % images.length; // Make sure x is never larger than images.length
img.src = images[x];
}
// Start calling the function after a delay of 3000ms
setInterval(imageChanger, 3000);​​​​
I also recommend using a better name than x for your counter variable, but that is up to you!
You're close. You need to change two things.
First, you need to call the imageChanger function at least once to kick off the code. At the end of your script, add:
imageChanger();
Your code may work from there. However, instead of passing a string to setTimeout(), you should instead pass a reference to the function itself:
setTimeout(imageChanger, 3000);
You should be all set. Let me know if you have issues.
Remove
setTimeout("imageChanger()", 3000);
And add
window.onload=function() {
setInterval(imageChanger, 3000);
}
Outside the function
And as pointed out, change > to >=

Background Image/Color Changing

As part of my website projects, I would like to add a script, javascript or whatever, that changes the background image, but the problem is, I'm don't know how to program with Java. I only know Lua, HTML, & CSS.
The reason for that is because I'd like the background image to change after 5 seconds (fades into another image) and then again to another. A loop.
I have found something but it's said that it doesn't work:
<script language="JavaScript">
var Rollpic1 = "1.jpg";
var Rollpic2 = "2.jpg";
var Rollpic3 = "3.jpg";
var PicNumber=1;
var NumberOfPictures=3;
var HowLongBetweenPic=5;
function SwitchPic(counter){
if(counter < HowLongBetweenPic){
counter++;
document.roll.src = eval("Rollpic" + PicNumber);
CallSwitchPic=window.setTimeout("SwitchPic("+counter+")",1500);
}
else{
if(PicNumber < NumberOfPictures){
PicNumber++;
SwitchPic(0);
}
else{
PicNumber=1;
SwitchPic(0);
}
}
}
</script>
<body onload="SwitchPic(0)">
<img src="1.jpg" height="300" width="400" border="0" name="roll">
This will do it:
<script>
document.body.style.backgroundImage="url('path/to/background.png')";
</script>
Or if you want it to happen when you click something:
<script>
function change() {
document.body.style.backgroundImage="url('path/to/background.png')";
}
</script>
<input type="button" onclick="change()" value="Change it" />
To have some code loop on a timer:
<script>
function timedCount() {
// some code here
setTimeout("timedCount()",1000); //1000 milliseconds
}
</script>
Run that function ^ somehow (like with the onclick hander of a button as shown above) and it will loop forever, executing the function every 1000 ms
By the way, Java has nothing to do with Javascript. They're completely separate and are very different.
You can use CSS with Javascript to accomplish this easily like this:
<style>
.myImageClass { background-image: url(images/header.jpg); }
.extraClass { background-image: url(images/extra.jpg); }
</style>
<script type="text/javascript">
function changeMyBackground(elementID, myClassName = 'myImageClass'){
document.getElementById(elementID).className=myClassName;
}
// Change BG of element with id bgImage with the default class 'myImageClass'
changeMyBackground('bgImage');
// or change the bg of the element with id bgImage using a custom class.
changeMyBackground('bgImage', 'extraClass');
</script>
Define an ID to the element like this:
<body id="bgImage">
CONTENT
</body>
Is there a reason your not setting the background image in CSS?
Using jQuery is very easy, for example if you wanted to set a background on the body
$("body").css("background","url('images/bg.png')");
And don't forget to include jQuery in your header by:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
Maybe this will do:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var imageIndex = 0;
var imagesArray = new Array();
//Set Images
imagesArray[0] = "images/one.png";
imagesArray[1] = "images/two.png";
imagesArray[2] = "images/three.png";
function changeBackground(){
$("body").css("background","url('"+ imagesArray[imageIndex] +"')");
imageIndex++;
if (imageIndex > imageArray.length)
imageIndex = 0;
}
$(document).ready(function() {
setInterval("changeBackground()",5000);
});
</script>
</head>
To achieve a fade out transition to a new image you are better using an image tag . Inserting the new image with a lower z-index than the old image so it sits behind it. Next you fade out the old image and update the z-index of the new image.
I would recommend using JQuery cycle plugin (http://jquery.malsup.com/cycle/) because it will be easier for you to follow. Your code would therefore be:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src=”jquery.cycle.all.js” type=”text/javascript”></script>
<script type=”text/javascript”>
$(document).ready(function() {
$(‘.pics’).cycle({
fx: ‘fade’,
speed: 5000
});
});
</script>
</head>
<body>
<div class=”pics”>
<img src=”image/one.png” />
<img src=”image/two.png” />
<img src=”image/three.png” />
</div>
</body>
</html>

Categories

Resources