I'm trying to implement a timer that will swap the larger image with the next image in line, I feel like I'm on the right track, but I'm not getting there. I can't use Jquery or (event.target), (event.srcElement) or appendChild. Any ideas? I don't think my function is doing anything right now. Current code below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Photo Gallery</title>
<script>
var aryImages[] = {"1.jpg", "2.jpg", "3.jpg"}
function changeImage(varImage) {
document.getElementById('bigImage').src='images/1.jpg';
for (var i = 1; i < 4; i ++)
index.html = "images/1.jpg" + photoOrder[i] +"sm.jpg";
}
</script>
/* styling elements */
<style>
img
{
width: 300px;
height: 290px;
padding: 2px;
}
body
{
text-align: center;
background-color: black;
}
</style>
</head>
<body>
<div>
<img src="images/1.jpg" id="bigImage" />
</div>
<img src='images/1.jpg' id='image1' onclick="changeImage(image1)" />
<img src='images/2.jpg' id='image2' onclick="changeImage(image2)"/>
<img src='images/3.jpg' id='image3' onclick="changeImage(image3)"/>
</body>
</html>
This should be what you're looking for. I set an interval that will rotate through your images. If the user clicks an image, that will change the image and reset the interval.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Photo Gallery</title>
<script>
var i = 1;
function changeImage(event, varImage) {
document.getElementById('bigImage').src='images/' + varImage + '.jpg';
// use this so the image interval doesnt
// interfere with user's click
if (event !== null) {
clearInterval(newInt);
newInt = setInterval(() => {
changeImage(null, i++);
if (i === 4) i = 1;
}, 500);
}
}
var newInt = setInterval(() => {
changeImage(null, i++);
if (i === 4) i = 1;
}, 500)
</script>
/* styling elements */
<style>
img
{
width: 300px;
height: 290px;
padding: 2px;
}
body
{
text-align: center;
background-color: black;
}
</style>
</head>
<body>
<div>
<img src="images/1.jpg" id="bigImage" />
</div>
<img src='images/1.jpg' id='1' onclick="changeImage(event, 1)" />
<img src='images/2.jpg' id='2' onclick="changeImage(event, 2)"/>
<img src='images/3.jpg' id='3' onclick="changeImage(event, 3)"/>
</body>
</html>
first of all you are not changing anything
you dont have a timer at all :)
here how to implement one:
setInterval(function(){
// do something;
}, 3000);
now inside the timer you should change images
for example
you should run inspect element on image to see changes because there is no images at these sources
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var currentImage = 0;
// assuming that image is the image index in the array.
var changeImage = function (image) {
document.getElementById('bigImage').src = 'images/' + images[image];
};
// now we can use setInterval function
setInterval(function(){
// check if we reached the last image
if(currentImage >= images.length -1) {
// if last image go back to first one
currentImage = 0;
} else {
// if not last image so give me the next
currentImage ++;
}
// do the image change
changeImage(currentImage);
}, 3000);
<img src="images/image1.jpg" id="bigImage" />
<button onclick="changeImage(0)" > image1 </button>
<button onclick="changeImage(1)" > image2 </button>
<button onclick="changeImage(2)" > image3 </button>
Related
I created a whack a mole game. However, I am trying to add the Price is Right theme to the background as the user plays the game. Is there anything I need to add to the javascript to make this happen? I have the mp3 file saved inside of a sounds folder.
Here is the index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Whack A Mole</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Whack a Skeletor!</h1>
<h2>Your Score:</h2>
<h2 id="score">0</h2>
<h2>Seconds Left:</h2>
<h2 id="time-left">60</h2>
<div class="grid">
<div class="square" id="1"></div>
<div class="square" id="2"></div>
<div class="square" id="3"></div>
<div class="square" id="4"></div>
<div class="square" id="5"></div>
<div class="square" id="6"></div>
<div class="square" id="7"></div>
<div class="square" id="8"></div>
<div class="square" id="9"></div>
</div>
<script src="app.js"></script>
</body>
</html>
Here is the JavaScript file
const squares = document.querySelectorAll('.square');
const mole = document.querySelector('.mole');
const timeLeft = document.querySelector('#time-left');
const score = document.querySelector('#score');
let result = 0;
let hitPosition;
let currentTime = 60;
let timerId = null;
let evilLaugh = new Audio('sounds/laugh.mp3');
evilLaugh.volume = 0.3;
function randomSquare() {
squares.forEach((square) => {
square.classList.remove('mole');
});
let randomSquare = squares[Math.floor(Math.random() * 9)];
randomSquare.classList.add('mole');
hitPosition = randomSquare.id;
}
squares.forEach((square) => {
square.addEventListener('mousedown', () => {
if (square.id == hitPosition) {
result++;
score.textContent = result;
hitPosition = null;
}
});
});
function moveMole() {
timerId = setInterval(randomSquare, 500);
}
moveMole();
function countDown() {
currentTime--;
timeLeft.textContent = currentTime;
if (currentTime == 0) {
clearInterval(countDownTimerId);
clearInterval(timerId);
alert('GAME OVER! Your final score is ' + result);
evilLaugh.play();
}
}
let countDownTimerId = setInterval(countDown, 1000);
Here is the CSS file
* {
background-color: black;
color: red;
}
.square {
width: 200px;
height: 200px;
border-style: solid;
border-color: lime;
}
.grid {
display: flex;
flex-flow: row wrap;
justify-content: center;
align-content: center;
width: 618px;
height: 618px;
}
.mole {
background-image: url(skeletor.jpeg);
background-size: cover;
}
What you're doing with evilLaugh is the same thing that you would do with your Price is Right sound. The only addition would be that we would need some way to repeat the song each time it ends, which is well covered in this Stack Overflow question. So you could do:
let myPriceAudio = new Audio('sounds/nameOfFile.mp3');
myPriceAudio.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
myPriceAudio.play();
The linked Stack Overflow question does say that all major browsers support myPriceAudio.loop = true;, so you could also do that instead of the .addEventListener() functionality.
I have a few URLs that each show the status of some industrial equipment. I'm trying to create an HTML/Javascript solution that, on load, cycles through each of the websites at a set interval, with two buttons to stop the cycle (to take a closer look at something) and restart the cycle (either from the beginning or where it left off, I'm not picky). I'm REALLY rusty, but I got what I think is a good start. Unfortunately, it doesn't work. Here are the CSS and HTML:
html,
body {
height: 100vh;
width: 100vw;
}
#btStart {
position: absolute;
width: 50px;
height: 40px;
left: 20px;
top: 50px;
}
#btStop {
position: absolute;
width: 50px;
height: 40px;
left: 20px;
top: 120px;
}
#infoFrame {
width: 100%;
height: 100%;
}
.holder {
width: 100%;
height: 100%;
position: relative;
}
<!DOCTYPE HTML>
<html>
<head>
<title>Info Cycle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="main.css" rel="stylesheet">
</head>
<body>
<div class="holder">
<iframe src="" id="infoFrame" frameborder="0" allowfullscreen>
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var i = document.getElementById('infoFrame');
var u = document.getElementById('url');
var timer = setInterval(cycleTimer, 5000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1)? -1 : count;
return url;
}
function cycleTimer() {
u.innerHTML = '';
i.src = nextUrl();
i.onload = function(){
u.innerHTML = i.src;
}
}
</script>
</iframe>
<button type="button" id="btStart" onclick="var timer = setInterval(cycleTimer, 5000);">Start</button>
<button type="button" id="btStop" onclick="clearInterval(timer)";>Stop</button>
</div>
</body>
<footer>
</footer>
</html>
Before I added the buttons it would load, then 5 seconds later it would cycle correctly, and so on. Now it only shows the buttons. Looking at the requests, I believe what's happening in my CSS and structure is trash, and it's loading the appropriate URL, but not displaying. I should add, prior to the buttons I only had the iframe with the script in it as a proof of concept. I div'd it, added the stylesheet, and added the buttons, and now here we are.
This may be a rookie mistake, or something more complicated. I haven't done development in a long time, and I'm just trying to solve a little problem at work. If you could spare a minute, I'd be happy to know how to fix this, and also any feedback on what I could be doing better. I'd love to get back into doing more of this, so I'm interested to learn anything the community can share. I've searched the site and the internet, and I've found a couple of related solutions but nothing for this in particular.
Thanks!
EDIT:
In case it helps, below is the HTML before the buttons and stylesheet, which worked (it rotated between webpages every 7 seconds):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Info Cycle</title>
</head>
<body>
<iframe id="frame" src=""
style="
position: fixed;
top: 0px;
bottom: 0px;
right: 0px;
width: 100%;
border: none;
margin: 0;
padding: 0;
overflow: hidden;
z-index: 999999;
height: 100%;
"></iframe>
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var i = document.getElementById('frame');
var u = document.getElementById('url');
var timer = setInterval(cycleTimer, 7000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1)? -1 : count;
return url;
}
function cycleTimer() {
u.innerHTML = '';
i.src = nextUrl();
i.onload = function(){
u.innerHTML = i.src;
}
}
</script>
</body>
</html>
The iframe style was something I found in an old file I'd written (probably copied and pasted from Stack Overflow to just get a thing to work).
The problem here is having the script inside the iframe. If you move your script out of the iframe and put it under body or head then it will work.
<!DOCTYPE HTML>
<html>
<head>
<title>Info Cycle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="main.css" rel="stylesheet">
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var timer = setInterval(cycleTimer, 5000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1) ? -1 : count;
return url;
}
function cycleTimer() {
var i = document.getElementById('infoFrame');
var u = document.getElementById('url');
u.innerHTML = '';
i.src = nextUrl();
i.onload = function () {
u.innerHTML = i.src;
}
}
</script>
</head>
<body>
<div class="holder">
<iframe src="" id="infoFrame" frameborder="0" allowfullscreen>
</iframe>
<button type="button" id="btStart" onclick="var timer = setInterval(cycleTimer, 5000);">Start</button>
<button type="button" id="btStop" onclick="clearInterval(timer)" ;>Stop</button>
</div>
</body>
<footer>
</footer>
</html>
I tried searching for "file name changes to 0 in browser" both in Google and here, but got nowhere. This is a simple file which suddenly stopped opening. I can't even get at the inspector to troubleshoot it. Undo/redo history is lost, so that will not help. I'm guessing it's a simple mistake, but I have NEVER seen this before.
<!doctype html>
<html lang="en">
<head>
<title>JS Animated Navigation Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
<!--
var location = 0;
var bar = document.getElementById("bar1");
function myMove()
{
// if (id != 0) clearInterval(id);
location = -144;
// if (location != -144) return; // don't execute onmouseover while previous onmouseover is still running.
id = setInterval(move, 1);
}
function move()
{
location++;
bar.style.left = location + 'px';
if (location == 300)
{
clearInterval(id);
id = setInterval(moveback, 1);
}
}
function moveback()
{
location--;
bar.style.left = location + 'px';
if (location == -144)
{
clearInterval(id);
// id = setInterval(move, 1);
}
}
-->
</script>
<style>
#container
{
width: 600px;
height: 100px;
position: relative;
background: white;
}
#bar1
{
width: 150px;
height: 30px;
position: absolute;
left: -144px;
background-color: white;
}
</style>
</head>
<body>
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id ="container">
<div id ="animate"><img src="imageGalleryBar.png" alt="Image Gallery" width="150" height="30" id="bar1" onmouseover="myMove()" /></div>
</div>
</body>
</html>
Thank you
You can't use the variable name location as it is a reserved word; what you're actually doing is setting the window.location variable to 0.
Rename it, or put it in a namespace or object.
I need to change the image source onClick, for that i created the jquery click and the image source is not effecting until the click completes
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.bg {
background-image: url("paper.gif");
background-color: #cccccc;
}
</style>
<script>
$(document).ready(function(){
$("a").click(function(){
//alert($("#img").attr("src"));
$("#img").attr("src","https://www.w3schools.com/images/driveicon.png");
//alert($("#img").attr("src"));
$("h1").attr("class","");
//alert('hi');
sleep(10000000);
//alert('hi1');
});
});
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
</script>
</head>
<body>
<h1 class="bg">Hello World!</h1>
<a>
<img id="img" src="https://tpc.googlesyndication.com/daca_images/simgad/16193915113295470335?w=195&h=102"/>
</a>
<br>
<p id="img1"/>
</body>
</html>
In the above code, image src changing after few seconds of the click.
I need to change the image source immediately after click.
Thanks in advance
Your problem is because Javascript is single-threaded. Hence while the massive loop in your sleep() function is running nothing else can happen. In turn, this means that the DOM does not get time to render the change you made to the src of the img element, and it only appears to occur once the loop terminates.
The way to solve this is to make use of one of the timer functions which JS provides. In your case setTimeout() would be the most appropriate:
$(document).ready(function() {
$("a").click(function() {
$("#img").attr("src", "https://www.w3schools.com/images/driveicon.png");
$("h1").attr("class", "");
setTimeout(doSomethingElse, 1000);
});
});
function doSomethingElse() {
console.log('Doing something else here...');
}
.bg {
background-image: url("paper.gif");
background-color: #cccccc;
}
#img {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 class="bg">Hello World!</h1>
<a>
<img id="img" src="http://i.imgur.com/HazyBBo.jpg" />
</a><br />
<p id="img1" />
I am trying to set up a javascript/jquery to display rotating images, infact I am trying to put anything I can on top of my multiple image background... I was able to make a mock banner and that was a success but I can't place an unordered list, a picture or the rotating images on my site.
my html is
<link rel="stylesheet" type="text/css" href="styles/main.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="/javascript/main.js" type="text/javascript"></script>
</head>
<body>
<div id="massiveWrapper">
<div id="header">
<img src="/images/banner.png" alt="banner" width="1024px" height="150px"/>
</div>
<div id="menu">
<ul>
<li>hello</li>
<li>hello</li>
</ul>
</div>
<div id="rotatingWrapper">
<img class="rotateImage" src="/images/blue.png" alt="Computers" width="1024px" height="200px" />
<img class="rotateImage" src="/images/red.png" alt="Computers" width="1024px" height="200px" />
<img class="rotateImage" src="/images/green.png" alt="Computers" width="1024px" height="200px" />
</div>
<div>
<img src="/images/blue.png" alt="blue" width="1024px" height="200px"/>
</div>
</div>
</body>
</html>
my css is
body {
background: url(/images/background-top.png) 0 0 repeat-x,
url(/images/menu.png) 0 160px repeat-x,
url(/images/background-middle.png) 0 210px repeat-x;
background-color: #dadada;
}
#massiveWrapper {
width: 1024px;
margin: auto;
}
#rotatingWrapper {
width: 1024px;
height: 200px;
}
.rotateImage {
display: none;
position: absolute;
top: 0;
left: 0;
}
and javascript is
$(window).load(function() { //start after HTML, images have loaded
var InfiniteRotator =
{
init: function()
{
//initial fade-in time (in milliseconds)
var initialFadeIn = 1000;
//interval between items (in milliseconds)
var itemInterval = 5000;
//cross-fade time (in milliseconds)
var fadeTime = 2500;
//count number of items
var numberOfItems = $('.rotateImage').length;
//set current item
var currentItem = 0;
//show first item
$('.rotateImage').eq(currentItem).fadeIn(initialFadeIn);
//loop through the items
var infiniteLoop = setInterval(function(){
$('.rotateImage').eq(currentItem).fadeOut(fadeTime);
if(currentItem == numberOfItems -1){
currentItem = 0;
}else{
currentItem++;
}
$('.rotateImage').eq(currentItem).fadeIn(fadeTime);
}, itemInterval);
}
};
InfiniteRotator.init();
});
I really want to be able to have the rotating images I just cant for the life of me add anything new to the page. I have even added a dummy picture using div and img but that also wont show up... this is probably something small but yer I am new to coding.
Kane
You shouldn't add px to the width and height attributes of your images.
For example:
<img src="/images/banner.png" alt="banner" width="1024px" height="150px"/>
should be:
<img src="/images/banner.png" alt="banner" width="1024" height="150"/>