I am having issues getting a button to work. I want something to happen when I click this button:
<button id="pigBtn" value="click">Pig It!</button>
and my JS file has
window.addEventListener('load', function(){
console.log('hello');
let pigBtn = document.querySelector('#pigBtn');
console.log('pigged');
pigBtn.addEventListener('click', function (){
function pigIt(phrase) {
let array = phrase.split(' ');
console.log('array');
for (let i = 0; i < phrase.length; i++) {
let pig = array[i].split('');
let one = pig.shift();
pig.push(one);
pig.push('ay');
let two = pig.join('');
array[i] = two;
}
return array.join(' ');
}
});
});
'hello' and 'pigged' show up but 'array' does not. What am I missing here?
The button has id pigBtn, but you try to select an element with id pigged.
Try this instead:
let pigBtn = document.querySelector('#pigBtn');
window.addEventListener('load', function(){
console.log('hello');
let pigBtn = document.querySelector('#pigBtn');
console.log('pigged');
pigBtn.addEventListener('click', function (){
console.log('clicked');
});
});
<button id="pigBtn" value="click">Pig It!</button>
window.addEventListener('load', function(){
console.log('hello');
let pigBtn = document.querySelector('#pigBtn');
console.log('pigged');
pigBtn.addEventListener('click', function (){
console.log('clicked');
});
});
The ID in your querySelector has to match the ID of the button in your HTML.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
Your pigIt function is never executed. You define it in your event handler, but you never run it.
I think you're going for something like this :
window.addEventListener('load', function(){
var sentence = "This is the phrase I'm pigging";
console.log('hello');
let pigBtn = document.getElementById('pigBtn');
let pigTxt = document.getElementById('phraseTxt');
let pigPhraseTxt = document.getElementById('pigPhraseTxt');
console.log('pigged');
pigBtn.addEventListener('click', function(e) {
let array = pigTxt.value.split(' ');
for (let i = 0; i < array.length; i++) {
let pig = array[i].split('');
let one = pig.shift();
pig.push(one);
pig.push('ay');
let two = pig.join('');
array[i] = two;
}
pigPhraseTxt.value = array.join(' ');
});
});
input {
display : block;
width : 100%;
padding: 0;
border: 1px solid #aaa;
}
input:read-only {
background: #ddd;
}
<input type="text" id="phraseTxt" value="This is the text I'm converting to Pig Latin" />
<input type="text" id="pigPhraseTxt" readonly />
<button id="pigBtn" value="click">Pig It!</button>
Related
//* I am trying to click on an image and it counts the clicks*//
var addUp = function(counterId) {
var count = 0;
elem.addEventListener('click', function(counterID){
return function () {
var counterEle = document.getElementById(counterId);
if (counterEle)
counterEle.innerHTML = "Picture Clicks: " + ++count;
}
};
var elem = document.getElementById('PicC');
PicC.addEventListener("click", addUp("PicC-counter"), false);
<img id="PicC" src="avatar.png" alt="Avatar" style="width:200px" onclick="addUp()">
function clickCount(element, listener) {
if (!element) throw new Error("No element to listen to");
let clickCountObj = {};
clickCountObj.clickCount = 0;
clickCountObj.clickDelay = 500;
clickCountObj.element = element;
clickCountObj.lastClickTime = 0;
let clickCountListener = function (e) {
if ((e.timeStamp - clickCountObj.clickDelay) < clickCountObj.lastClickTime) {
clickCountObj.clickCount = clickCountObj.clickCount + 1;
}
else {
clickCountObj.clickCount = 1;
}
clickCountObj.lastClickTime = e.timeStamp;
listener.call(element, clickCountObj.clickCount, e);
};
clickCountObj.remove = function () {
element.removeEventListener("click", clickCountListener);
}
element.addEventListener("click", clickCountListener);
return clickCountObj;
}
You've made it much more complex than it needs to be.
const output = document.getElementById("count");
document.getElementById('PicC').addEventListener("click",function(event){
output.textContent = +output.textContent + 1;
});
<img id="PicC" src="avatar.png" alt="Avatar" style="width:200px">
<div>Click count = <span id="count">0</span></div>
Here's what went wrong, as far as I can tell:
addEventListener was inside a function
addEventListener doesn't accept function parameters
count was being reset every click
and more
You can simply hook up the event listener to a function that'll increment clicks and add the value to the click counter.
var clicks = 0;
document.getElementById("clickme").addEventListener("click", addClick);
function addClick() {
clicks++;
document.getElementById("clickCounter").innerHTML = "Picture Clicks: " + clicks;
}
#clickme {
background-color: black;
width: 100px;
height: 100px;
<div id="clickme"></div> <!-- replaced with div for convenience -->
<div id="clickCounter">Picture Clicks: 0</div>
There's no need of addEventListener for such a simple task.
My suggestion (no CSS added):
var i = 1;
PicC.onclick = () => {
counter.innerHTML = i;
i++;
}
<img id="PicC" src="https://via.placeholder.com/150" alt="Avatar">
<br>
<div>Click(s): <span id="counter">0</span></div>
I was wondering how it is possible to make the button undo something too after clicking it. In my scenario just simple formatting of Text(Color,size etc), when you first click it, it formats the text as described in Javascript, but I would like to add a function, that when you click it again, that it undoes that.
`<script>
function myFunction(){
document.getElementById("demo").style.fontsize="25px";
document.getElementById("demo").style.color="#3AF702";
document.getElementById("demo").style.backgroundcolor="red";
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
I checked other articles already, which seemed to be related, but I did not get any smarter out of those, so my apologies in advance if it is a dup and thanks for your help!
<script>
var flag = true;
function myFunction(){
let el = document.getElementById("demo");
el.style.fontsize = flag ? "25px" : "";
el.style.color= flag ? "#3AF702" : "";
el.style.backgroundcolor=flag ? "red" : "";
flag = !flag;
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
The easiest way to do this is to add and remove a class
<style>
.change {
font-size: 25px;
color: #3AF702;
background-color="red"
}
</style>
<script>
var x = 0;
function myFunction() {
if (x == 0) {
document.getElementById("demo").classList.add("change");
x = 1;
} else {
document.getElementById("demo").classList.remove("change");
x = 0;
}
}
</script>
<button type="change" onclick="myFunction()">Change!</button>
Create an object that stores the initial values of your button and a variable which holds the state of it.
var state = 0;
var backup = {};
backup.fontSize = document.getElementById("demo").style.fontsize;
backup.color = document.getElementById("demo").style.color;
backup.background = document.getElementById("demo").style.backgroundcolor;
Now you can easily switch between the backup and the new values like this:
function myFunction() {
if (state == 0) {
document.getElementById("demo").style.fontsize = "25px";
document.getElementById("demo").style.color = "#3AF702";
document.getElementById("demo").style.backgroundcolor = "red";
state = 1;
} else {
document.getElementById("demo").style.fontsize = backup.fontSize;
document.getElementById("demo").style.color = backup.color;
document.getElementById("demo").style.backgroundcolor = backup.background;
state = 0;
}
}
var flag = true;
function myFunction(){
var x = document.getElementById("demo");
if (flag) {
x.style.backgroundColor = "red";
x.style.color="#3AF702";
x.style.fontSize="25px"
} else {
x.style.backgroundColor = "blue";
x.style.color="#dddddd";
x.style.fontSize="10px"
}
flag = !flag
}
function myFunction(){
demo.className = demo.className ? "" : "style"
}
.style {
font-size: 25px;
color: red;
background: blue;
}
<p id="demo">Hi!</p>
<button type="change" onclick="myFunction()">Change!</button>
Im working on a checklist chrome app for myself and would love your help. Basically, I cant figure out how to save a checkbox status. If I check a box and refresh the page, I would like it to stay checked. But I cant seem to code that. Any ideas how to do that? Thank you!!
Edit: I added the html, it gives me the message that my post is mostly code and that I need to add some text, so here I am just writing some more to fulfil this requirement. There is no need reading this. Thanks for the help and sorry for the late edit
function get_todos() {
var todos = new Array;
var todos_str = localStorage.getItem('todo');
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
function add() {
var task = document.getElementById('task').value;
var todos = get_todos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function remove() {
var id = this.getAttribute('id');
var todos = get_todos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function show() {
var todos = get_todos();
var html = '<ul>';
for(var i=0; i<todos.length; i++) {
html += '<li>' + '<input type="checkbox" id="checkbox">' + todos[i] + '<button class="remove" id="' + i + '">delete</button></li>' ;
};
html += '</ul>';
document.getElementById('todos').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for (var i=0; i < buttons.length; i++) {
buttons[i].addEventListener('click', remove);
};
}
document.getElementById('add').addEventListener('click', add);
show();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
</head>
<body>
<style>
html,body,h1,h3,h4,h6 {font-family: "Roboto";font-size: 24px; sans-serif}
h2 {font-family: "Roboto";font-size: 36px; sans-serif}
h5 {font-family: "Roboto";font-size: 28px; sans-serif}
</style>
<input id="task"><button id="add">Add</button>
<hr>
<div id="todos"></div>
<script src="todo.js"></script>
</body>
</html>
Seeing as no one else has provided an answer, I thought I'd throw in my potential solution, I went with a functional style because why not, it's simple, easy to read, etc...
PS
I included the fallback variable because on Stack Overflow, you can't access local storage when running a snippet.
let fallback = [];
const $e = query => document.querySelector(query);
// Return a todo list.
const getToDoList = () => {
let data = null;
try {
data = JSON.parse(localStorage.getItem('todo'));
} catch (e) {
data = fallback;
}
return data == null || Array.isArray(data) == false ? [] : data;
};
// Set the todo list.
const setToDoList = (data) => {
try {
localStorage.setItem('todo', JSON.stringify(data));
} catch (e) {
fallback = data;
}
};
// Add a task to the todo list.
const addToDo = () => {
const array = getToDoList();
array.push({value: $e("#task").value, checked: false});
setToDoList(array);
};
// Remove a task from the todo list.
const removeToDo = index => {
const array = getToDoList();
array.splice(index, 1);
setToDoList(array);
};
// Allow for the ability to remove an item from the todo list & other stuff..
const dispatchListEvents = () => {
document.querySelectorAll('#app ul li span').forEach(span => {
span.onclick = () => {
removeToDo(span.parentElement.getAttribute('data-index'));
render();
}
});
document.querySelectorAll('#app ul li input').forEach(input => {
input.onclick = () => {
const array = getToDoList();
const object = array[input.parentElement.getAttribute('data-index')];
object.checked = ! object.checked;
setToDoList(array);
render();
}
});
};
// Render the todo list.
const render = () => {
let index = 0;
const template = item => `<li data-index="${index++}">` +
`<input type="checkbox" ${item.checked ? 'checked' : ''} />` +
`${item.value} <span>X</span></li>`;
const re = new RegExp('</li>,', 'g'), replacement = '</li>';
const html = `<ul>${getToDoList().map(i => template(i))}</ul>`;
$e("#app").innerHTML = `${html.replace(re, replacement)}`;
dispatchListEvents();
};
// Allow the user to add a task to the todo list.
const addToListClickHandler = () => {
let result = $e("#task").value.replace(/\ /g, '').length > 0 ? addToDo() : null;
$e("#task").value = null; // Always null as addToDo returns null.
render();
};
// The function that will be fired when the DOM is ready.
const ready = () => {
render(); // Initial render.
$e("#addToList").addEventListener('click', addToListClickHandler);
};
// An insanely lazy implementation of $(document).ready.
const delay = 250;
const fakeOnReady = setTimeout(ready, delay);
body {
font-family: Arial, Helvetica, sans-serif;
}
#app ul li {
max-width: 150px;
}
#app ul li span {
float: right;
color: red;
}
#app ul li span:hover {
cursor: pointer;
}
<h1>To Do List</h1>
<section>
<h2>Add Task</h2>
<input id="task" placeholder="Task..."/>
<input type="button" id="addToList" value="Add"/>
</section>
<hr/>
<section>
<h2>Tasks</h2>
<div id="app">
<!-- Area for the DHTML. -->
</div>
</section>
How do I make reference to the specific dashes I created, and add a
specific letter to them. Read the comments and code to get a better
context. Thanks for any help in advance!!
<!Doctype html>
<html lang="en">
<head>
<style>
ul {
display: inline;
list-style-type: none;
}
.boxes {
font-size:1.6em;
text-align:center;
width: 10px;
border-bottom: 3px solid black;
margin: 5px;
padding: 10px;
display: inline;
}
.hidden {
visibility: hidden;
}
.visible {
visibility: visible;
}
</style>
</head>
<body>
<script>
var possibleWord = ["COW", "BETTER", "HARDER", "JUSTIFY", "CONDEMN",
"CONTROL", "HELLO", "UNDERSTAND", "LIFE", "INSIGHT","DATE",
"RIGHTEOUSNESS"];
var hangmanWord = possibleWord[Math.floor(Math.random() *
possibleWord.length)];
var underlineHelp;
var space;
var guess;
var guesses = [];
var placement;
var underscores = [];
var character = [];
var textNodes = [];
window.onload = function () {
placement = document.getElementById('hold');
underlineHelp = document.createElement('ul');
placement.appendChild(underlineHelp);
for (i = 0; i < hangmanWord.length; i++) {
underscores = document.createElement('li');
underscores.setAttribute('class', 'boxes');
guesses.push(underscores);
underlineHelp.appendChild(underscores);
character = document.createElement('span');
character.appendChild(document.createTextNode(hangmanWord[i]));
character.classList.add('hidden');
underscores.appendChild(character);
}
This is the area I want to refer to later.
for(x=1;x<=26;x++){
document.getElementById("test").innerHTML = hangmanWord;
var btn = document.createElement("BUTTON");
var myP = document.createElement("br");
var letter = String.fromCharCode(x+64);
var t = document.createTextNode(letter);
btn.appendChild(t);
btn.id = letter;
Just creating buttons. This is important when I say 'this.id' down below.
btn.addEventListener("click", checkLetter);
document.body.appendChild(btn);
//add a line break 'myP' after 3 buttons
if (x%10==0) {
document.body.appendChild(myP);
}
}
}
function checkLetter(){
//this refers to the object that called this function
document.getElementById("p1").innerHTML += this.id;
for (i = 0; i < hangmanWord.length; i++) {
guess = hangmanWord[i];
if (this.id == guess) {
character[i] = hangmanWord[i];
character.appendChild(document.createTextNode(hangmanWord[i]));
character.classList.add('visible');
}
}
}
Here is where I am in trouble. If I do this (the code I wrote after the if statement) the letters will be added on the end of the string. I Want to have it on the specific dashes that I created earlier. How can I manage to do that? Do I have to do something called "object passing." I am relatively new to js (high school student) and I am keen on any insight! Once again thanks for the help in advance!
</script>
</head>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<div id = "contents">
<div id = "hold"></div>
</div>
<p id ="p1"> Letters picked: </p>
<div id= "picBox"></div>
<div id = "test"></div>
</div>
</body>
You could store the guessing word and the guessed characters in an object and just output the replaced result of such instead. Seems easier to me.
<html>
<head>
<script>
//The hangman object
var Hangman = {
wordToGuess: 'RIGHTEOUSNESS', //The word to guess. Just one for my example
guessedLetters: [] //The guessed characters
};
window.onload = function(){
//Creating the buttons
for(var tF=document.createDocumentFragment(), x=1; x<=26; x++){
var tLetter = String.fromCharCode(x+64),
tButton = tF.appendChild(document.createElement("button"));
tButton.id = tLetter;
tButton.addEventListener("click", checkLetter);
tButton.appendChild(document.createTextNode(tLetter));
(x%10 === 0) && tF.appendChild(document.createElement('br'))
};
document.body.appendChild(tF);
startTheGame()
};
//Starts a game of hangman
function startTheGame(){
var tWord = Hangman.wordToGuess,
tPlacement = document.getElementById('hold');
document.getElementById('test').innerHTML = tWord;
//Resetting the guesses
Hangman.guessedLetters = [];
//Creating dashes for all letters in our word
for(var i=0, j=tWord.length; i<j; i++){
tPlacement.appendChild(document.createTextNode('_'))
}
}
function checkLetter(){
var tButton = this,
tLetter = tButton.id,
tWord = Hangman.wordToGuess,
tPlacement = document.getElementById('hold');
//Make a guess
document.getElementById('p1').innerHTML += tLetter;
(Hangman.guessedLetters.indexOf(tLetter) === -1) && Hangman.guessedLetters.push(tLetter.toLowerCase());
//Clear the current word
while(tPlacement.firstChild) tPlacement.removeChild(tPlacement.firstChild);
//Now we reverse replace the hangman word by the guessed characters
for(var i=0, j=tWord.length; i<j; i++){
tPlacement.appendChild(document.createTextNode(
(Hangman.guessedLetters.indexOf(tWord[i].toLowerCase()) === -1) ? '_' : tWord[i]
))
}
}
</script>
</head>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<div id = 'contents'>
<div id = 'hold'></div>
</div>
<p id = 'p1'> Letters picked: </p>
<div id= "picBox"></div>
<div id = "test"></div>
<!-- This one seems to be too much
</div>
-->
</body>
</html>
https://jsfiddle.net/zk0uhetz/
Update
Made a version with propert object handling, separating the actual hangman logic from the interface.
<html>
<head>
<style>
button{
margin: 1px;
min-width: 30px
}
button[disabled]{
background: #777;
color: #fff
}
</style>
<script>
//Handles the hangman game itself
;(function(ns){
'use strict';
var _listOfWord = ['COW', 'BETTER', 'HARDER', 'JUSTIFY', 'CONDEMN', 'CONTROL', 'HELLO', 'UNDERSTAND', 'LIFE', 'INSIGHT','DATE', 'RIGHTEOUSNESS'],
_wordToGuess = null, //The word to guess. Just one for my example
_guessedLetters = [] //The guessed characters
ns.Hangman = {
//Returns the current obstructed word
getCurrentObstructedWord: function(){
var tWord = []; //The current state of the game
if(_wordToGuess){
//Now we reverse replace the hangman word by the guessed characters
for(var i=0, j=_wordToGuess.length; i<j; i++){
tWord.push(
(_guessedLetters.indexOf(_wordToGuess[i].toLowerCase()) === -1) ? '_' : _wordToGuess[i]
)
}
};
return tWord
},
//Make a guess at the current game
Guess: function(letter){
//Add the guess to the list of guesses, unless already guessed
(_guessedLetters.indexOf(letter) === -1) && _guessedLetters.push(letter.toLowerCase());
return this.getCurrentObstructedWord()
},
isComplete: function(){
return !!(this.getCurrentObstructedWord().indexOf('_') === -1)
},
//Starts a new game
Start: function(){
_guessedLetters = []; //Resetting the guesses
_wordToGuess = _listOfWord[Math.floor(Math.random() * _listOfWord.length)];
return _wordToGuess
}
}
}(window._ = window._ || {}));
//Creates the buttons for hangman
function createButtons(){
var tContainer = document.querySelector('#buttons');
while(tContainer.firstChild) tContainer.removeChild(tContainer.firstChild);
//Creating the buttons
for(var tF=document.createDocumentFragment(), x=1; x<=26; x++){
var tLetter = String.fromCharCode(x+64),
tButton = tF.appendChild(document.createElement('button'));
tButton.id = tLetter;
tButton.addEventListener('click', makeAGuess);
tButton.appendChild(document.createTextNode(tLetter));
(x%10 === 0) && tF.appendChild(document.createElement('br'))
};
tContainer.appendChild(tF)
};
//Makes a guess
function makeAGuess(){
var tButton = this,
tLetter = tButton.id;
//Disable the button
tButton.setAttribute('disabled', 'disabled');
//Make a guess
var tElement = document.getElementById('hold');
tElement.textContent = _.Hangman.Guess(tLetter).join('');
//Check if finished
if(_.Hangman.isComplete()){
tElement.style.color = 'limegreen'
}
};
//Starts a new game of hangman
function Reset(){
createButtons(); //Recreated the buttons
_.Hangman.Start(); //Starting a game of hangman
var tElement = document.getElementById('hold');
tElement.textContent = _.Hangman.getCurrentObstructedWord().join('');
tElement.style.color = ''
};
window.onload = function(){
Reset()
};
</script>
</head>
<body>
<div id = 'hold'></div>
<p id = 'p1'>Make a guess:</p>
<div id = 'buttons'></div>
<br /><br />
<button onclick = 'Reset()'>Start a new game</button>
</body>
</html>
https://jsfiddle.net/mm6pLfze/
In the following example I try with a next-button that changes the text next to the radio-buttons also to load the corresponding audio files.
The sound later corresponds to a question. The user answers with the radio-button and clicksNext. The next question should be played and at the same time the answers next to the radio-buttons change. The selection of the answers (radio-buttons) should be transferred to an external script in a second step.
At the moment, the dynamic lyrics work well, but the sound can not yet be loaded properly to match the text array. clip1 to arr1, clip2 to arr2 and clip3 to arr3
Does anyone have a better solution for that? Many Thanks
//////////Text Array1//////////
var arr1 = [
"Argument arr1,1",
"Argument arr1,2",
"Argument arr1,3",
"Argument arr1,4",
];
var i1 = -1;
function nextItem1() {
i1 = i1 + 1; // increase i by one
i1 = i1 % arr1.length
return arr1[i1]
}
function prevItem1() {
if (i1 === 0) { // i would become 0
i1 = arr1.length
}
i1 = i1 - 1; // decrease by one
return arr1[i1];
}
window.addEventListener('load', function () {
document.getElementById.textContent = arr1[0]; // initial value
document.getElementById('prev_button').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById('arr1').textContent = prevItem1();
}
);
document.getElementById('next_button').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById('arr1').textContent = nextItem1();
//document.querySelector('#clip1').click;
}
);
});
//////////Text Array2//////////
var arr2 = [
"Argument arr2,1",
"Argument arr2,2",
"Argument arr2,3",
"Argument arr2,4",
];
var i2 = -1;
function nextItem2() {
i2 = i2 + 1;
i2 = i2 % arr2.length
return arr2[i2];
}
function prevItem2() {
if (i2 === 0) { // i would become 0
i2 = arr2.length
}
i2 = i2 - 1; // decrease by one
return arr2[i2];
}
window.addEventListener('load', function () {
document.getElementById.textContent = arr2[0]; // initial value
document.getElementById('prev_button').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById('arr2').textContent = prevItem2();
}
);
document.getElementById('next_button').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById('arr2').textContent = nextItem2();
}
);
});
//////////Text Array3//////////
var arr3 = [
"Argument arr3,1",
"Argument arr3,2",
"Argument arr3,3",
"Argument arr3,4",
];
var i3 = -1;
function nextItem3() {
i3 = i3 + 1;
i3 = i3 % arr3.length
return arr3[i3];
}
function prevItem3() {
if (i3 === 0) { // i would become 0
i3 = arr3.length
}
i3 = i3 - 1; // decrease by one
return arr3[i3];
}
window.addEventListener('load', function () {
document.getElementById.textContent = arr3[0]; // initial value
document.getElementById('prev_button').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById('arr3').textContent = prevItem3();
}
);
document.getElementById('next_button').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById('arr3').textContent = nextItem3();
}
);
});
//////////Load Sound Clips//////////
var listener = new THREE.AudioListener();
var audioLoader = new THREE.AudioLoader();
var clip1 = document.querySelector('#clip1');
clip1.addEventListener('click', function () {
loadClip('https://cdn.rawgit.com/mrdoob/three.js/master/examples/sounds/358232_j_s_song.mp3');
});
var clip2 = document.querySelector('#clip2');
clip2.addEventListener('click', function () {
loadClip('https://cdn.rawgit.com/mrdoob/three.js/master/examples/sounds/376737_Skullbeatz___Bad_Cat_Maste.mp3');
});
var clip3 = document.querySelector('#clip3');
clip3.addEventListener('click', function () {
loadClip('https://cdn.rawgit.com/mrdoob/three.js/master/examples/sounds/358232_j_s_song.mp3');
});
//////////End Sound Clips//////////
var audioLoaded = false,
result
function loadClip( audioUrl ) {
audioLoaded = false
console.log(`\nLoading sound...`);
audioLoader.load( audioUrl, function( buffer ) {
sound = new THREE.PositionalAudio( listener );
sound.setBuffer( buffer );
sound.setRefDistance( 20 );
sound.setLoop(false);
sound.setVolume(5);
console.log(`\nAudio finished loading!`);
audioLoaded = true
});
play.onclick = function playClip() {
console.log( `\nplayClip()` );
play.style.background = "#92ddb8";
reset.disabled = false;
play.disabled = true;
paused.disabled = false;
sound.play();
}
reset.onclick = function resetClip() {
console.log( `\nresetClip()` );
play.style.background = "";
play.style.color = "";
stop.disabled = true;
play.disabled = false;
paused.disabled = false;
sound.stop()
document.getElementById('radio1').checked = false;
document.getElementById('radio2').checked = false;
document.getElementById('radio3').checked = false;
console.clear()
}
paused.onclick = function pausedClip() {
console.log( `\npausedClip()` );
play.style.background = "";
play.style.color = "";
stop.disabled = false;
play.disabled = false;
paused.disabled = true;
sound.pause();
}
}
#arr1 {
font-family:Arial,sans-serif;
font-size: 1em;
color:black;
margin-top: -20px;
margin-left: 30px;
}
#arr2 {
font-family:Arial,sans-serif;
font-size: 1em;
color:black;
margin-top: -20px;
margin-left: 30px;
}
#arr3 {
font-family:Arial,sans-serif;
font-size: 1em;
color:black;
margin-top: -20px;
margin-left: 30px;
}
<script src="//cdn.rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
<input type="radio" id="radio1" name="myCheckbox" autocomplete="off" onclick="myCheckbox"/>
<p id="arr1">load audio 1 for test</p>
<input type="radio" id="radio2" name="myCheckbox" autocomplete="off" onclick="myCheckbox"/>
<p id="arr2">load audio 2 for test</p>
<input type="radio" id="radio3" name="myCheckbox" autocomplete="off" onclick="myCheckbox"/>
<p id="arr3">load audio 3 for test</p>
<button id="play" class="play">Play</button>
<button id="paused" class="paused">Pause</button>
<button id="reset" class="reset">Reset</button>
<input type="button" id="prev_button" value="<< Prev" onclick="prev_button">
<input type="button" id="next_button" value="Next >>" onclick="next_button">
<p id="clip1"></p>
<p id="clip2"></p>
<p id="clip3"></p>