I am new to JS and I have a pretty simple-seeming problem.
I want to have a small image that when clicked changes to a different image and at the same time begins playing a looped sound file. When the image is clicked a second time it changes back to the original image and also stops the sound file.
You can think of it as a button that says "start". when "start" is clicked it loops the sound and changes to "stop" and when "stop" is clicked it goes back to start and the sound ceases playing.
I've gotten as far as creating none-displayed checkbox inside of a label which is a square that when checked plays sound and when unchecked stops sound. Problem is I can't get the checkbox to change into different images with "check", "uncheck".
I've also got some code that has a link change images, but I cannot figure out how to make it play the sound.
SO basically i need to combine these two things. BUT I CAN'T figure out how. And I've been googling for the past two days nonstop but cannot find a clearcut and simple answer.
It may help to know that I plan on having many of these small clickable images on the same page, so the Javascript needs to be able to be light but effect all of the links or divs or whatever they are in the end.
Sorry for such a long question. Anybody?
Thanks in advance!
<html>
<head>
<script type="text/javascript">
var pos = 0
var sId = 'sound';
function change() {
if(pos == 0) {
pos = 1;
document.getElementById('btn').src="http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png";
var e = document.createElement('embed');
e.setAttribute('src','beep.mp3');
e.setAttribute('id',sId);
e.setAttribute('hidden','true');
e.setAttribute('autostart','true');
e.setAttribute('loop','true');
document.body.appendChild(e);
} else {
pos = 0;
document.getElementById('btn').src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png";
document.body.removeChild(document.getElementById(sId));
}
}
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="change()" id="btn" />
</body>
</html>
How about that, I think it should work.
Edit:
Here is an OO version that should do what you need:
<html>
<head>
<script type="text/javascript">
function imageSwitch(_imgID,_imgStart,_imgStop,_soundFile) {
this.imgID = _imgID;
this.imgStart = _imgStart;
this.imgStop = _imgStop;
this.soundFile = _soundFile;
this.pos = 0;
this.e;
this.change = function() {
if(this.pos == 0) {
this.pos = 1;
document.getElementById(this.imgID).src = this.imgStop;
this.e = document.createElement('embed');
this.e.setAttribute('src',this.soundFile);
this.e.setAttribute('id','sound'+this.imgID);
this.e.setAttribute('hidden','true');
this.e.setAttribute('autostart','true');
this.e.setAttribute('loop','true');
document.body.appendChild(this.e);
} else {
this.pos = 0;
document.getElementById(this.imgID).src = this.imgStart;
this.e.parentNode.removeChild(this.e);
}
}
}
</script>
<script type="text/javascript">
var abc = new imageSwitch('btn1','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
var def = new imageSwitch('btn2','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="abc.change()" id="btn1" />
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="def.change()" id="btn2" />
</body>
</html>
Related
I've been given two examples of how to do this but neither is doing both things that I'm looking to do. My website should include:
Rotating Image Banner (3 images), that changes every few seconds
Each image should be clickable and redirect you to a different URL
In our recent lecture, the professor wrote this code on the board and said that this was how you did that. However, it's not working for me.
<html>
<head>
<script language=JAVASCRIPT type=TEXT/JAVASCRIPT>
//I'm not sure when to use '' or ""
//I replaced some of the "picture.jpg" images with links to images. I'm not sure if I used the right syntax.
adImages = new Array("https://i.picsum.photos/id/666/800/200.jpg",
"https://i.picsum.photos/id/420/800/200.jpg",
"https://i.picsum.photos/id/888/800/200.jpg");
adURL = new Array("https://google.com","https://github.com","https://stackoverflow.com");
thisAd = 0;
//length of what?
imgCt = adImages.length;
function rotate()
{
if (document.images)
{
thisAd++;
//Is it better practice to use "==="?
if (thisAd == imgCt)
{
thisAd = 0;
}
document.adBanner.src=adImages[thisAd];
setTimeout("rotate()", 2 * 1000);
}
}
function newLocation()
{
document.location.href = adURL[thisAd];
}
</script>
</head>
//I don't understand what this is at all
<body onload=rotate()>
//Apparently <center> is obsolete?
<center>
<p><font size=4>Rotating Banner <font color=#ff0000>Assignment 6</font> Rotate Party -
Udemy</font>
</p>
<a href="javascript:newLocation()"><IMG height=105 alt="Ad Banner"
src="https://i.picsum.photos/id/666/800/200.jpg" width=610 name=adBanner></a>
</center>
</body>
</html>
Just a heads up. I've been posting my slides from class on Reddit the past couple of weeks and I've received a lot of comments about things being horribly out of date. If you can, please give me examples that are more modern or better practices than what you see me learning. You can find the conversations about my experience learning JavaScript in community college here if you're interested: https://www.reddit.com/user/gettupled/
The second example we were given was a YouTube video that gave the following example. However, it does not include the option of clicking the image and being sent to a URL. I'm not sure if it's common to post HTML, CSS and Javascript code in the body of a message so I'll just attach a codepen unless told otherwise. This code comes from Travesy Media.
https://codepen.io/vitalwheat/pen/QWbEyqN
Thanks everyone. This is my first post here. Hi.
There are many way to implement this. Here is one of the way to do it.
working Demo
(function() {
"use strict";
const imageList = [
"https://i.picsum.photos/id/666/800/200.jpg",
"https://i.picsum.photos/id/420/800/200.jpg",
"https://i.picsum.photos/id/888/800/200.jpg"
];
const urlList = [
"https://google.com",
"https://github.com",
"https://stackoverflow.com"
];
function createRotatingBanner(rotationTime) {
const $adsBanner = document.querySelector(".adBanner");
let $bannerList;
let currentBannerRendered = 0;
function renderBanner() {
Array.from($bannerList).forEach((banner, bannerIndex) => {
banner.className = bannerIndex === currentBannerRendered ? "" : "hide";
});
currentBannerRendered = (currentBannerRendered+1)%$bannerList.length;
}
// creating Banner image and setting them to hide
function createBanner() {
const fragement = new DocumentFragment();
imageList.forEach((image, index) => {
const banner = document.createElement("img");
banner.src = image;
// wrapping image with anchor element
const anchor = document.createElement("a");
anchor.href = urlList[index];
// hide all the banner
anchor.className = "hide"
anchor.appendChild(banner);
fragement.appendChild(anchor);
});
const cloneFragement = [...fragement.children];
$adsBanner.appendChild(fragement);
return cloneFragement;
}
$bannerList = createBanner();
renderBanner();
setInterval(renderBanner, rotationTime);
}
createRotatingBanner(2000);
})();
.hide {
display: none;
}
<div class="adBanner"></div>
I'm working on a video game project and I'm not too sure how to set up the if statement because I'm new to programming. I want to have a picture to pop up only after the countdown reaches its last digit or value.
I have the countdown code working great, but I need to have the picture to pop up at the right location. I'm not sure how to add the value towards this location with the if statement. Basically when I click a button it's switch the background image therefore It wouldn't be a very good game if a random picture pops up while I'm looking at the wrong background.
I feel like I should add a value whenever I click the button and the value will change whenever I click on a different button. I just don't know how to set up the value and have it equal to true.
Also is there a way to reset the countdown?
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" seconds";
if(secs < 1) {
clearTimeout(timer);
element.innerHTML = '<h2>Countdown Complete!</h2>';
element.innerHTML += 'Click here now';
$("#black").show(0.1);
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
$(function(){
$("#black").hide(0.01);
})
function goodtogo(){
var good = true;
}
</script>
<body>
<div id="status"></div>
<script>countDown(2, "status");</script>
<img id="black" src="black1.jpg">
<input type="button" name="button" value="btn" onclick="goodtogo()">
</body>
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);
I've got a soundboard I use at work to annoy coworkers. It has multiple buttons, that play or stop a sound. Right now each button has its own script to play the sound. So I'm up to 47 sounds on the page and have to write this script for each one. I'd like to clean that up and have a one smarter script that works for all of them.
my buttons look like:
<button onclick="javascript:toggleSound1();">I don't know what we're yelling about.</button>
Then I have the definition of the audio element:
<audio id="sound1" src="sounds/dontknowwhatwereyellingabout.wav"></audio>
and the script:
<script type="text/javascript">
function toggleSound1() {
var audioElem = document.getElementById('sound1');
if (audioElem.paused)
audioElem.play();
else
audioElem.pause(); audioElem.currentTime = 0;
}
</script>
So it seems to me that if i could define the 'sound1' on the press in each button the same script should work for each button. as I have it now I have to define 'sound1' 'sound2' 'sound3' and so on, and point a new 'togglesound' at each of them.
You could rewrite toggleSound1 to take an argument:
function toggleSound(num) {
var audioElem = document.getElementById('sound' + num); // append the number to "sound" (sound1, sound2, etc.)
if (audioElem.paused) {
audioElem.play();
} else {
audioElem.pause();
}
audioElem.currentTime = 0;
}
Then to use it, you could just pass the number to the function:
<button onclick="javascript:toggleSound(1);">I don't know what we're yelling about.</button>
I'm not sure how I feel about encouraging this, but...
<button onclick="toggleSound('sound1');">I don't know what we're yelling about.</button>
<button onclick="toggleSound('sound2');">Some other sound</button>
<script type="text/javascript">
function toggleSound1(soundId) {
var audioElem = document.getElementById(soundId);
if (audioElem.paused)
audioElem.play();
else
audioElem.pause(); audioElem.currentTime = 0;
}
</script>
a better way is to use event delegation, and put the event handler higher up
<div onclick="handleAudio(e)">
<button data-audio="1">I don't know what we're yelling about.</button>
<button data-audio="2">Some other sound</button>
</div>
function handleAudio(e) {
var audio = document.getElementById('sound' + e.target.dataset.audio);
audio.play();
}
I'm trying to display one image in loop. Knowing the path and image-name are okay is this example, how to display one image in loop, and when the image haven't been found, the browser displays the last right image-name until the image-name is found?
#{int j=1;}
<img src="" />
<script>
(function () {
for (var i = 1; true; i++) {
#{ string file = "/MonitoringN/../bitmaps/" + j + ".png"; bool a = System.IO.File.Exists(file) == true; }
var str = "/MonitoringN/../bitmaps/" + i + ".png";
var b = "#a";
if (b)
{
setInterval(function () { $('img').prop('src', str); }, 1000);
} else {
i--;
#{j--;}
}
#{j++;}
}
});
</script>
Because when I execute this code, I get a blank image, and then I can't see the page is loading.
Thanks a lot!
I think I know what you are trying to do ...
If I understand the question correctly, you have a list of images and you want to try to open them until one of them is found. If an image is NOT found, you want to skip to the next one.
First -- I'd simply for your question by separating the Razor stuff and the Javascript off into very separate pieces. In fact, I'm going to skip Razor entirely.
<html>
<head>
<title>A test</title>
</head>
<body>
<img src="http://x.invalid" id="myImage">
<script>
var imgs = [
"http://x1.invalid/none",
"https://www.google.com/images/srpr/logo11w.png",
"http://thedailywtf.com/Resources/Images/Primary/logo.gif"
];
var imageIndex = 0;
function tryNextImage() {
var img = document.getElementById("myImage");
img.onerror = function() {
imageIndex++;
tryNextImage();
}
img.src = imgs[imageIndex];
}
// start the ball rolling
tryNextImage();
</script>
</body>
</html>