How to make an image play sound onclick using JavaScript? - javascript

So I want to create my 1st project using JS HTLM and CSS, which will be like a drum website ...
when I click on an image it should make sound . So, All I know is making a button make sound by clicking on it not an actual image. If you have any idea what should I put in this YYY place ?
here's my JS file code :
PS : soundi is this image's class
var soundi = document.querySelectorAll(".soundi").length;
for (var i = 0; i < soundi ; i++) {
document.querySelectorAll(".soundi")[i].addEventListener("click", function () {
var clickDe = this.YYYY;
switch (clickDe) {
case "YYYY" :
var tom1 = new Audio('sounds/tom-1.mp3');
tom1.play();
break;
}
})
}

You could add an Id to each image and then register the event listeners like so:
function imageClicked(event) {
const imgId = event.target.id; // imgId is the name of the instrument => the name of the sound file without the extension
const soundFile = new Audio(`sounds/${imgId}.mp3`); // this way, you don't have to use a switch statement which can get very long and chaotic
soundFile.play();
}
document
.querySelectorAll(".soundi") // querySelectorAll returns all the images so no need to put it in a for loop
.forEach((img) => img.addEventListener("click", imageClicked));
You will obviously have to choose the image ids properly so that they match up with the file names.

Related

JavaScript Change Images Path That Have The Same Id

I want to make a JavaSript code that changes the images. I mean there are two images and a button. The images path are /assets/images/svg/outline-img1.svg and /assets/images/svg/outline-img.svg. Also there is a button, that should change all the images path that have the same id (id="changeimg").
I want to make that when you click onto the button, it should change the images, that contains the changeid. It's pretty simple but what I really want is to only change a part of the path. I mean I want to change the path from /assets/images/svg/outline-img1.svg to /assets/images/svg/filled-img.svg. But is it possible to change all the images' path that contain the changeimg id?
Is there any code snippet for example this?
document.querySelector('.btn').addEventListener("click",
function () {
$('#changeimg').attr('src', '/assets/images/svg/filled-'+imgname+'.svg');
/*
imgname should be the name of the image between the '/assets/images/svg/outline' and the '-.svg'. (In this example imgname = shape and imgname = shape2)
So the it should change the elements that contains the '#changeimg' id from '/assets/images/svg/outline-shape.svg' to '/assets/images/svg/filled-shape.svg'
And all the images with the changeimg id should be changed.
*/
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/assets/images/svg/outline-shape.svg" id="changeimg">
<img src="/assets/images/svg/outline-shape2.svg" id="changeimg">
<button class="btn">Change</button>
I know it's a bit hard to understand, if you want I can redefine my problem.
First, IDs should be unique. You might even get warnings if not doing so.
Use classes, and then
const elements = document.getElementByClassName('changeimg')
for (let i=0; i< elements.length; i ++) {
const imgPath = elements[i].src;
imgPath.replace('outlined', 'filled');
elements[i].src = imgPath;
}
Try this,
const x = document.querySelectorAll("#changeimg");
for (i = 0; i < x.length; i++) {
x[i].src = "/assets/images/svg/filled-img.svg";
}

Setting a onClick function to a dynamically created button, the function fires onload

I am currently creating a program which utilizes localStorage to create a site with a wishlist like functionality. However when I go to generate the html page that should create the wishlist with the photo of the item, the name and a button to remove said item from the list. But when I go to assign the onClick functionality to the button, the function fires on page load rather then on click. I have four main java script functions, one to add to the localstorage, one to remove from local storage, a helper function for removing and the one that will generate the wishlist page (where the problem is).
function genWishListPage(){
for (var i = 0; i < localStorage.length; i++) {
var item = getWishlist(i);
var name = document.createElement("p");
var removeButton = document.createElement("button");
var image = document.createElement("img")
image.src = item.image;
removeButton.innerText = "Remove from wishlist";
removeButton.onClick = RemoveFromWishList(item.name);
removeButton.setAttribute("ID","remove");
name.innerText = item.name;
document.body.appendChild(image);
document.body.appendChild(name);
document.body.appendChild(removeButton);
document.body.appendChild(document.createElement("BR"));
//removeButton.setAttribute("onclick", RemoveFromWishList(item.name));
//removeButton.addEventListener('click', RemoveFromWishList(item.name));
//document.getElementById("remove").addEventListener("click",RemoveFromWishList(item.name));
}
}
The commented parts are ways I have already tried and gotten the same bug.
Any help or advice is appreciated.
When you write
removeButton.onClick = RemoveFromWishList(item.name); you are assigning the return value of the function call to the onClick event. Instead you can write
removeButton.onClick = function() { RemoveFromWishList(item.name);}
You should assign a function to the onClick event listener.

Dynamically change image in javascript

JavaScript Noob here.
I want to show the dynamically changing image effect like this:
http://dotsignals.org/google_popup.php?cid=202
(if this webpage cannot show changing image, click on any camera at http://dotsignals.org)
I have examined the code, and have some questions:
1.The website uses setImage and refreshSetImage to initialize and refresh the image for a dynamically changing effect. What is the use of Math.random in here? I understand it is a way to differentiate images from different time at the same cam. But how does it works? How would the backend respond?
2.Related to the first question. What is the mechanism of the refreshSetImage? I didn't see any sign of requesting data from the server. Does it send a "GET"? How does it refresh the image?
function setImage(imageID){
var currentImage = imageID;
document.getElementById(currentImage).src ='http://207.251.86.238/cctv9.jpg'+'?math=';
refreshSetImage();
}
function refreshSetImage() {
document.images["myCam"].src = 'http://207.251.86.238/cctv9.jpg'+'?math='+Math.random();
setTimeout('refreshSetImage()',1000);
}
function ScaleSize(imageID) {
var elem = document.getElementById(imageID);
elem.style.width = 500;
elem.style.height = 300;
}
3.How is the backend designed?
4.Now I want to use these two functions in my own project. I want to add a parameter of camID in the setImage and refreshSetImage functions, so the src of the image will change to something like: 'http://..../'+camID+'.jpg'+'?math'. camID is a String that identifies different cameras. I changed it to:
function refreshSetImage(camID) {
document.images["myCam"].src = 'http://207.251.86.238/'+camID+'.jpg'+'?math='+Math.random();
setTimeout('refreshSetImage(camID)',1000);
}
function setImage(imageID,camID){
var currentImage = imageID;
document.getElementById(currentImage).src = 'http://207.251.86.238/'+camID+'.jpg'+'?math=';
refreshSetImage(camID);
}
and got an error :Uncaught ReferenceError: camID is not defined VM132:1. The image is not changing as well. I don't know what is the problem. What is VM132:1 ?
Thanks
check
function refreshSetImage(imageID,camID) {
currentImage = imageID;
url = 'http://207.251.86.238/'+camID+'.jpg'+'?math='+Math.random();
//document.getElementById(currentImage).src= url;
console.log(url);
}
$(document).ready(function(){
imageID = "imageID";
camID = "camID";
setInterval(function() {
refreshSetImage("imageID","camID");
}, 3000);
});
https://jsfiddle.net/Cuchu/vr1ftwg1/

get name of files in a folder with javascript

I have a background image folder that there is some picture that i want to use them for background.
how i can get their names and put them on array whit javascript?if i cant they do with javascript,how can i do that?
i want to read name of files and use javacsript and link for change background image whit css.
<script>
function nextbg(){
$('#bg').css('background-image','url(Images/bg2.jpg)');
}
</script>
This solution is created according to the fact that browser dont have access to folders/filesystem.
Javascript can not access the filesystem. This has to be done by a server script and then be feed to the javascript.
I had the simliar problem when building my game engine when I was loading all my diffrent tiles. I ended up doing it like this.
This solution do pose two a problems when implementing it.
You will have to define the amout of images in the "NrofTiles" array
The images must be named like tile1, tile2 ... tile9 so you can
increment the path to them.
The typeOfTiles[typeCounter] is just there to give me access to different folders, in my case for my tiles, grass, houses, water and so on.
for(var i = 0; i <= nrofTiles.length; i++)
{
for(var x = 0; x <= nrofTiles[i]; x++)
{
console.log
("Fetching tile "+(x + 1 )+" of " + 14);
img = new Image();
//My path
img.src = 'Images/Cart/' + typeOfTiles[typeCounter] + '/' + (x + 1) + '.png';
imgArray.push(img);
var intervalFunctionen = function () {
alert("calls back here");
};
}//end for loop!
}end outer for loop!
When everything is loaded(the tiles), you do this to change the background picture.
This is an example of a changing body background. You could make a link with an ID lets say "iamthelink".
HTML
Change BG
JAVASCRIPT
var link = document.getElementsById('iamthelink');
link.onclick= function() {
var body = document.getElementsByTagName('body')[0];
body.style.backgroundImage = 'url(http://localhost/background.png)';
}

javascript: multiple stop image toggle

I am trying to make an image button on my website toggle wallpaper change frequency options (off,5,10,15,30,30,90 minutes). I have created a custom image for each step (so the user can be aware of the current setting). When implemented the user should be able to repeatedly hit the button to toggle through all 7 options, ultimately looping back to the beginning.
I have some code to swap between two images (below), and have used it for other options on the site (wallpaper on/off), but I just can't figure out a way to get the code to work for my new needs.
if (imageId == 'image1') {
if (document.getElementById) {
var img = document.getElementById(imageId);
img.src = (img.src.indexOf("40_unlocked.jpg") != -1) ? "40_locked.jpg" : "40_unlocked.jpg";
}
}
I expect I will need to determine the current image, then use a switch to advance to the next option, something like the below, but I don't know how to determine the current image - hoping someone can offer a suggestion - thanks in advance!
function changeIt(img) {
var src;
switch (img.id) {
case "example":
src = "n.gif";
break;
case "example2":
src = "n2.gif";
break;
case "example3":
src = "n3.gif";
break;
}
img.src = (img.src.indexOf("jj.gif") < 0 ? "jj.gif" : src);
}
This should get you started
Name your images n0.gif through n6.gif.
toggle.onclick=function(){
//isolate the number of the current image
var num=this.src.split('.gif')[0].split('n')[1]-0;
//add 1 and take mod 7 to loop it back to 0 if it needed
num=++num%7;
//set the src to the new image
this.src='n'+num+'.gif';
}
Try creating an array of all of the src urls & then toggle it like this.
function changeIt(img)
{
var src=img.src;
images=['src1','src2','src3','src4','src5','src6','src7'];
index=images.indexOf(a);
if (index+1>6)
{
index=0;
}
else
{
index+=1;
}
img.setAttribute('src',images[index]);
}

Categories

Resources