Javascript slideshow array issue - javascript

I'm pretty new to Javascript and im trying to build slideshow myself now. Only im stuck right now after i build the array where i get my pictures from. It only shows a white screen.
My Javascript
$(function () {
var counter = 0;
var defaultSettings = {
"sliderContainer": "#slider"
, "pauseWithMouse": true
, "sliderSpeed": 2000
, "transitionSpeed": 1500
};
function cycleImages() {
counter++;
if (counter >= images.Length) {
counter = 0;
}
document.getElementById("#slider img").src = MyImages[counter];
var images = $('#slider img')
, now = images.filter(':visible')
, next = now.next().length ? now.next() : images.first()
, speed = 1500; //Transition speed
now.fadeOut(speed);
next.fadeIn(speed);
}
var theInterval; // Slide speed
var = images = [];
// if myImages exists then
images = myImages;
if (images.length > 0) {
$(defaultSettings.sliderContainer).append('<img id="sliderImage" src="' + images[0] + '" />');
startSlide();
}
var startSlide = function () {
setInterval(cycleImages, defaultSettings.sliderSpeed); // Set interval
};
var stopSlide = function () {
if (defaultSettings.pauseWithMouse) {
clearInterval(theInterval);
}
};
startSlide();
$('#slider img').on('mouseover', function () {
stopSlide();
});
$('#slider img').on('mouseout', function () {
startSlide();
});
});
And my HTML:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Javascript Slider</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="css/style.css">
<script src="js/slideshow.js"></script>
<script>
var myImages = ["slide1.jpg", "slide2.jpg", "bg/slide3.jpg"];
</script>
</head>
<body>
<main>
<div id="slider">
</div>
</main>
</body>
</html>

you have strange declaration of variable here
var = images = [];
also you need to move this part
var startSlide = function() {
setInterval(cycleImages, defaultSettings.sliderSpeed); // Set interval
};
before
if (images.length > 0) {
$(defaultSettings.sliderContainer).append('<img id="sliderImage" src="' + images[0] + '" />');
startSlide();
}
you have wrong variable name (MyImages) here
document.getElementById("#slider img").src = MyImages[counter];
first try to debug your code

Related

Make JavaScript change background image every 5 seconds

I am trying to change my background image every 5 seconds. How should I go about this?
window.onload = function () {
function Timer() {
window.setInterval("changeImage()", 5000);
}
function changeImage() {
var BackgroundImg["./Img/Bg1.jpg",
"./Img/Bg2.jpg",
"./Img/Bg3.jpg",
"./Img/Bg4.jpg"];
var i = Math.floor((Math.random() * 3));
var bgImg = document.body.style.backgroundImage();
bgImg.url = BackgroundImg[i];
}
}
You can make few changes
1.Not sure from where you are calling Timer function (better if
have camelCase)
function Timer() {
window.setInterval("changeImage()", 5000);
}
Instead you can directly use
setInterval(changeImage, 5000);
changeImage is a callback
2.Could not make out what is this line mean
var bgImg = document.body.style.backgroundImage();
Unsure if can attach a function to style property.
Anyway this below snippet can be useful
window.onload = function () {
// Array of Images
var backgroundImg=["https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyB57zuc4bms-hDtWMa-4BZvscIlJDm4r7a9WLaO4SAxUvKM-DDA",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQBinSpWOvAtkxjmkf709O3rjH2ObRbWAEn9s0JcWaeL6LMtCbOrQ",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRKY4J2qIFqkuDnABMzeypywbMSZL1cleS8vpySz0KD02wOYORU1g",
"https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRQkdQT0zN0xDVP-VuvwojSbS5dOstX14eZvJCOWNPxKJ5dWTIc"
]
setInterval(changeImage, 5000);
function changeImage() {
var i = Math.floor((Math.random() * 3));
document.body.style.backgroundImage = "url('"+backgroundImg[i]+"')";
}
}
DEMO
you are accessing style incorrectly
window.onload = function () {
function changeImage() {
var BackgroundImg=["./Img/Bg1.jpg",
"./Img/Bg2.jpg",
"./Img/Bg3.jpg",
"./Img/Bg4.jpg"
];
var i = Math.floor((Math.random() * 4));
document.body.style.backgroundImage = 'url("' + BackgroundImg[i] + '")';
}
window.setInterval(changeImage, 5000);
}
Also, if possible (usually is) don't pass a string to window.setInterval - use as above
Here's a solution to your question. Hope it helps!
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function changeImage() {
setInterval(displayNextImage, 5000);
}
var images = [], x = -1;
images[0] = "http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg";
images[1] = "http://www.planwallpaper.com/static/images/background-gmail-google-images_FG2XwaO.jpg";
images[2] = "http://www.planwallpaper.com/static/images/beautiful-sunset-images-196063.jpg";
</script>
</head>
<body onload = "changeImage()">
<img id="img" src="http://www.planwallpaper.com/static/images/beautiful-sunset-images-196063.jpg"/>
</body>
</html>

How to create a countdown timer before a function is performed

What I want to do is have a coin flip which will start a countdown when the flip button is pressed or if instructed to elsewhere. Then I want it to countdown 3, 2, 1 and display that on the screen. When the countdown is complete it will display heads or tails. The reason for this is so I do not have to create an animation of the coin flipping instead a delay to build the tension.
This is the code I have so far:
<html>
<head>
<title>Coin Toss </title>
<script>
function toss() {
if (Math.random()>.5) {
window.document.coin.src = "CT.jpg";
}
else {
window.document.coin.src = "T.jpg";
}
return false;
}
</script>
</head>
<body>
<img name="coin" src="questionmark.png">
<form action="" onSubmit="return toss();">
<input type="submit" value="TOSS">
</form>
</body>
</html>
Here's an example using setTimeout. In this instance I've removed the form as you don't strictly need it imo, and used event listeners so that the JS call is removed from the HTML.
HTML
<img id="coin"/><br/>
<button id="toss">Toss</button><br/>
<div id="count"></div>
JS
function toss() {
var div = document.getElementById('coin');
if (Math.random() > .5) {
coin.src = "CT.jpg";
} else {
coin.src = "T.jpg";
}
}
function countDown() {
var count = 3, timer;
var div = document.getElementById('count');
// if count is not 0, add the new count to the
// count element and loop again, reducing the count number
// otherwise erase the count element, clear the timeout
// and run the toss function
var loop = function loop (count) {
if (count > 0) {
div.textContent = count--;
timer = setTimeout(loop, 1000, count);
} else {
div.textContent = '';
clearTimeout(timer);
toss();
}
}
// start the countdown
loop(count);
}
var button = document.getElementById('toss');
button.addEventListener('click', countDown, false);
DEMO
you can do this with a setInterval, here is an example:
Javascript:
var current = 3;
var elem = document.getElementById('toss');
var intervalId = setInterval( function(){
if( current > 0 ){
elem.innerHTML = "<h1>" + current + "</h1>";
} else {
if( Math.random() > .5 ){
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1932%20Type%201%20Silver%20Washington%20Quarter%20Obv.png">';
} else {
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1988%20Type%202%20Clad%20Washington%20Quarter%20Reverse.png">';
}
clearInterval( intervalId );
}
current--;
}, 1000 ); // 1000 ms = 1s
HTML:
<div id="toss"><div>
Also here is a Fiddle so you can test it out and see what it does:
http://jsfiddle.net/Cedriking/cLs9r3m6/
For your second question (in the comment), do this:
<html>
<head>
<title>This is my title</title>
</head>
<body>
<div id="toss"></div>
<script type="text/javascript">
var current = 3;
var elem = document.getElementById('toss');
var intervalId = setInterval( function(){
if( current > 0 ){
elem.innerHTML = "<h1>" + current + "</h1>";
} else {
if( Math.random() > .5 ){
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1932%20Type%201%20Silver%20Washington%20Quarter%20Obv.png">';
} else {
elem.innerHTML = '<img src="http://www.thecoinspot.com/25c/1988%20Type%202%20Clad%20Washington%20Quarter%20Reverse.png">';
}
clearInterval( intervalId );
}
current--;
}, 1000 ); // 1000 ms = 1s
</script>
</body>
</html>

document.getElementById returns null for unknown reason

The code is for a slider to switch images. When I run the page I get this error:
Cannot set property 'onclick' of null.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Slider</title>
<link rel="stylesheet" type="text/css" href="sliderswag.css">
<script language="javascript" type="text/javascript" src="imgslidescript.js"></script>
</head>
<body>
<div id="box">
<img id="main" src="http://lmetar.com/oscar1.jpg">
<img id="left" src="http://lmetar.com/left.png">
<img id="right" src="http://lmetar.com/right.png">
</div>
JavaScript:
document.getElementById('left').onclick = slideChange;
document.getElementById('right').onclick = slideChange;
var slideNumber = 0;
function slideChange()
{
slideNumber += 1;
if (slideNumber > 3)
{
slideNumber = 1;
}
else
{
document.getElementById('main').src = 'http://lmetar.com/oscar' + slideNumber + '.jpg';
}
}
Move your script to the end of your page. You're running JavaScript on elements that don't yet exist.
Or wrap the code you have in a window.onload call which will execute the code after the window has loaded. Ex:
window.onload = function () {
document.getElementById('left').onclick = slideChange;
document.getElementById('right').onclick = slideChange;
var slideNumber = 0;
function slideChange() {
slideNumber += 1;
if (slideNumber > 3) {
slideNumber = 1;
} else {
document.getElementById('main').src = 'http://lmetar.com/oscar' + slideNumber + '.jpg';
}
}
};
Your JavaScript is loading before you content, therefore it is trying to find elements that do not exists. You have 2 options:
Move your <script> tag to the end of your page
Use the following to wait until the page has loaded before you execute your script
Code:
document.addEventListener("DOMContentLoaded", function(event) {
// Your Code Here
});

make progress bar on images loading with bootstrap/jquery

I try to make a progress bar with bootstrap css on images loading. For this, I use the following script :
<html>
<head>
<link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet"/>
<script type="text/javascript">
var n=0;
var c=0;
$('img').each(function() {
n++;
var tmpImg = new Image() ;
tmpImg.src = $(this).attr('src') ;
tmpImg.onload = function() {
c++;
};
});
var interval = setInterval(function() {
percent = n/100;
loaded = c/percent;
// for displaying purposes
setBar(getBar()+50)
// feed loaded var to the progressbar
if (loaded == 100) {
clearInterval(interval);
}
}, 1);
function setBar(n) {
var bar = document.getElementById('fabbar');
bar.style.width = n+'%';
}
function getBar() {
var bar = document.getElementById('fabbar');
return parseInt(bar.style.width);
}
</script>
</head>
<body>
<div class="progress progress-info progress-striped active">
<div class="bar" id='fabbar' style="width: 20%"></div>
</div>
But this doesn't work, i.e the progress bar doesn't progress. How could I do that ?
Try this (demo):
$(function () {
var n = 0,
$imgs = $('img'),
val = 100 / $imgs.length,
$bar = $('#fabbar');
$imgs.load(function () {
n = n + val;
// for displaying purposes
$bar.width(n + '%').text(n + '%');
});
});

javascript image slideshow works in all other browsers but not IE

I have an image slideshow which will work in any other browser I try but not in IE - it just does nothing but display the primary image. Please could someone tell me I not going mad and it is a simple fix that I can't see.
Many thanks
Mickeyjay.
Code below:
<div id="image_slide"><img src="images/.......jpg" id="slideit" name="slideit" border="0">
<script type="text/javascript">
var dimages=new Array();
var numImages=3;
dimages[0]=new Image();
dimages[0].src="images/.......jpg";
dimages[1]=new Image();
dimages[1].src="images/.......jpg";
dimages[2]=new Image();
dimages[2].src="images/.......jpg";
var curImage=-1;
function swapPicture()
{
if (document.images)
{
var nextImage=curImage+1;
if (nextImage>=numImages)
nextImage=0;
if (dimages[nextImage] && dimages[nextImage].complete)
{
var target=0;
if (document.images.slideit)
target=document.images.slideit;
if (document.all && document.getElementById("slideit"))
target=document.getElementById("slideit");
if (target)
{
target.src=dimages[nextImage].src;
curImage=nextImage;
}
setTimeout("swapPicture()", 1500);
}
else
{
setTimeout("swapPicture()", 150);
}
}
}
setTimeout("swapPicture()", 1500);
</script>
Try this simplified test, the idea is to load your pictures before start to swap, and will not need to test .complete that way.
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="image_slide"><img src="intro.jpg"
id="slideit" name="slideit" border="0"></div>
<script type="text/javascript">
var curImage = -1;
var numImages = 2;
var dimages = new Array();
function loadPictures()
{
dimages[0] = new Image();
dimages[0].src = "test1.jpg";
dimages[1] = new Image();
dimages[1].src = "test2.jpg";
setTimeout(swapPicture, 3000);
}
function swapPicture()
{
var nextImage = curImage + 1;
if (nextImage >= numImages)
nextImage = 0;
document.images.slideit.src = dimages[nextImage].src;
curImage = nextImage;
setTimeout(swapPicture, 1500);
}
setTimeout(loadPictures, 1500);
</script>
</body>
</html>

Categories

Resources