Can't make 2 buttons play 2 different songs on my HTML - html

Firstly, I'm super (SUPER) new to coding in general. I'm doing a college project for a site, and I wanted to make a certain page have 2 buttons that play songs, 2 different versions, one for each button. I copied the code from stack overflow, can't remember where but I'll be forever thankful for that one answer. I'm new to SO too so I hope I put the code here the right way :|
<!-- BTN1-->
<button id="ASong" onClick="playPause()" >
<audio
src="mp3/Persona_5_OST-_Beneath_the_Mask_(getmp3.pro).mp3"
autoplay
loop
></audio>
<img src="img/musica2.png" width="100px" align="left" margin-top="40px">
<br/>
</button>
<script>
var aud = document.getElementById("ASong").children[0];
var isPlaying = false;
aud.pause();
function playPause() {
if (isPlaying) {
aud.pause();
} else {
aud.play();
}
isPlaying = !isPlaying;
}
</script>
<!-- BTN1-->
<!-- BTN2-->
<button id="ASong2" onClick="playPause()" >
<audio
src="mp3/Persona_5_OST_-_Beneath_the_Mask_r_(getmp3.pro).mp3"
autoplay
loop
></audio>
<img src="img/musica2.png" width="100px" align="left" margin-top="40px">
<br/>
</button>
<script>
var aud = document.getElementById("ASong2").children[0];
var isPlaying = false;
aud.pause();
function playPause() {
if (isPlaying) {
aud.pause();
} else {
aud.play();
}
isPlaying = !isPlaying;
}
</script>
<!-- BTN2-->
The only thing I really tried was changing the ID name for the second song. What happens is. I choose a button and click it first. That one button, with that specific song is the one that'll play (edit, it's not the first one I click, it's only one of the songs :/ it switched which one it was when I changed the ID name) , even if I try to press the other button afterwards. It's like both of them become the same button, they function the same. What I wanted is that each one of them worked separately. I want to be able to click, start one song, pause it, click on the other button and start the other song, which is not what's happening right now. I hope that makes sense D=

I'm going to modernize this a bit. Inline event handlers listeners are not the way to go these days. I'' use addEventListener instead.
Next, I'm going to use one lot of code to handle the actions. One concept to get used to as you learn to program is DRY: Don't Repeat Yourself. To facilitate the state of your playback I'll use a data attribute on the button
/*Get the buttons*/
document.querySelectorAll(".playPause").forEach(function(el) {
/*Add a click event listener*/
el.addEventListener("click", function() {
/*Get the first audio tag in the clicked button*/
var aud = this.querySelector("audio");
/*Check the data attirbute on the button if playing*/
if (this.dataset.isplaying === "true") {
/*Debug line*/
console.log("Pausing " + aud.src)
/*Change the status of the data attribute*/
this.dataset.isplaying = "false";
/*Pause the audio element*/
aud.pause();
} else {
/*Debug line*/
console.log("Playing " + aud.src)
/*Change the status of the data attribute*/
this.dataset.isplaying = "true";
/*PLay the audio element*/
aud.play();
}
})
});
<button id="ASong" class="playPause" data-isplaying="false">
<audio
src="mp3/Persona_5_OST-_Beneath_the_Mask_(getmp3.pro).mp3"
autoplay
loop
></audio>
<img src="img/musica2.png" width="100px" align="left" margin-top="40px">
</button>
<button id="ASong2" class="playPause" data-isplaying="false">
<audio
src="mp3/Persona_5_OST_-_Beneath_the_Mask_r_(getmp3.pro).mp3"
autoplay
loop
></audio>
<img src="img/musica2.png" width="100px" align="left" margin-top="40px">
</button>

Related

I added an HTML button to my page, and if you click on it, it hides the button , but I want the button to be hidden for 11 hours

<button type="button"
style="background-color:skyblue; border-color:blue; color:white"
className="bn49"
onClick = "this.style.visibility= 'hidden'; window.open('https://frankvanasch.com/elementor-158/','_blank')"
>go
</button>
Reaching your objective with HTML and JavaScript might be impossible if you user know what they are doing.
If you want to hide the button for 11 hours, I'd use localStorage or a cookie to store its status, and to choose if you want to show the button.
And invert the logic, like the button must be hidden by default, and shown only if no interaction has been made, or if the last interaction was more than 11 hours ago.
Somthing like this, of course this snippet cannot run here because of SO localStorage restrictions.
$(".bn49").on("click", function(evt) {
let tgt = evt.target;
$(tgt).hide();
localStorage.setItem("bn49", new Date().toISOString());
window.open('https://frankvanasch.com/elementor-158/', '_blank');
});
$(function() {
let btnTime = localStorage.getItem("bn49");
if (btnTime) {
// there is a time stored, we'll check it
let t = new Date();
t.setHours(t.getHours() - 11);
if (new Date(btnTime).getTime() > t.getTime()) {
// 11 hours have passed, show the button
$(".bn49").show();
}
} else {
// there isn't a time stored, show the button
$(".bn49").show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" style="background-color:skyblue; border-color:blue; color:white; visibility: hidden;" className="bn49">go</button>

Hide div and store local storage not to show div on page refresh

I have an image button in a div when click I want to hide image button and somehow store to local storage not to show div again on page refresh.
<div class="whatsapp"><a href="https://chat.whatsapp.com/........." target="_blank">
<img src="/img/whatsapp_group.png" alt="Whatsapp Join Button"><div class="whatsappbut">To Find Out MORE!</div></a></div>
I added an ID(id="img-btn") to your div to use it in script tag. If user didn't click on your image button so far, localStorage.getItem('img-btn-clicked') will return null otherwise it'll return 'true'(as we set it in saveClicked function).
Just make sure to put the script tag before the body tag ends(or you can link a separated Javascript file).
<body>
<div id="img-btn" class="whatsapp">
<a href="https://chat.whatsapp.com/........." target="_blank">
<img src="/img/whatsapp_group.png" alt="Whatsapp Join Button" />
<div class="whatsappbut">To Find Out MORE!</div></a>
</div>
<script>
checkImgBtnClicked();
function checkImgBtnClicked() {
const clicked = localStorage.getItem('img-btn-clicked'); // if this is not set it will return null
if (clicked) {
document.getElementById('img-btn').style.display = 'none'; // hides the img-btn
} else {
// add event listener for image button click(saveClicked function will be executed if user clicks on image button
document.getElementById('img-btn').addEventListener('click', saveClicked);
}
}
function saveClicked() {
// set a flag in local storage that image button is clicked
localStorage.setItem('img-btn-clicked', 'true');
document.getElementById('img-btn').style.display = 'none'; // hides the img-btn after it gets clicked
}
</script>
</body>

How to make a button pattern?

I'm trying to make a little puzzle game in HTML5 and I'm having trouble figuring out how to make a puzzle. In the puzzle you have to click the squares in a certain order to beat it. I don't know how to make it to where you have to click the buttons in order and if you don't you'll lose.
<!DOCTYPE html>
<html>
<head>
<title>Room Two</title>
<link rel="stylesheet" type="text/css" href="youtubeGame.css">
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Tangerine|Inconsolata|Droid+Sans|Oxygen|Ubuntu|Coming+Soon">
</head>
<body>
<div id="content">
<h1 id="roomNum">Room 2</h1>
<p id="roomInfo">Once again the door seems to magically close behind
you.<br /> Unlike the stone floor from the previous room, this one is divided up
into wooden slabs.<br /> You press your foot onto a slab. It slides down, and an
arrrow shoots from the roof.<br /> You barely get out of the way but somehow you
dodge it. You tell yourself to watch your step...</p>
<p id="step"></p>
<p id="step2"></p>
<div class="menu-container" id="puzzle">
<div class="button-container">
1
2
3
4
5
6
7
8
9
</div>
</div>
</div>
<br><br>
<div id="death">
Try Again?
</div>
Next Room
<script type="text/javascript">
document.getElementById("death").style.display = "none";
document.getElementById("nextRoom").style.display = "none";
function correctStep1() {
return true;
}
function correctStep2() {
return true;
}
function correctStep3() {
return true;
}
function correctStep4() {
return true;
}
function correctStep5() {
return true;
}
function correctStep6() {
return true;
}
function correctStep7() {
return true;
}
function wrongStep() {
document.getElementById("content").style.display = "none;"
document.getElementById("puzzle").style.display = "none";
document.getElementById("death").style.display = "block";
document.getElementById("roomNum").innerHTML = "You Have
Died";
document.getElementById("roomInfo").style.display = "none";
}
</script>
</body>
</html>
Please help me fix this
A very simple way would be to save the correct order in an array and if the user clicks, increment a clickcounter and check if the clicked button is at this position in the array:
var state = {
clickedButtons:[]
};
var correctClickSettings = {
order:[7,8,9,6,5,2,3],
resetOn:7 // order has 7 elements, so the user have to click 7 buttons, after that it will be checked and the clicked buttons will be resolved or rejected
};
// called from every button that can be clicked to solve the game
function onClick(evt) {
evt = evt || window.event;
var sourceButtonText = this.innerText;
state.clickedButtons.push(sourceButtonText);
if(state.clickedButtons.length >= correctClickSettings.resetOn) {
var distanceBetweenArrays = state.clickedButtons.reduce((cur,val,idx)=>cur+Math.abs(val-correctClickSettings.order[idx]),0);
if(distanceBetweenArrays > 0) {
wrongStep();
state.clickedButtons = [];
} else {
alert('This was right!');
}
}
}
This solution has one problem: Everybody with a little bit of understanding for javascript can open the webpage and read out the solution. So if you want to do it a little better (not so easaly cheatable) you have to use another solution:
You can use a hash instead of an array of button clicks as correct order:
function simpleHash(currentHash, idx, sourceButtonText) {
currentHash = currentHash*137+parseInt(sourceButtonText,10);
}
Now simply calculate the correct solution value: 46672273550408 (in your case)
Now with every button click calculate the next hash and compare it after 7 steps with the solution.
This is a very similar approach to your current implementation, however uses attributes to declare the order of the options. It also does the binding of the events directly through javascript.
var options = [];
var expected = 0;
document.querySelectorAll('.button').forEach((button, index)=>{
options.push({
button: button,
order: button.getAttribute('order'),
index: index,
clicked: false
});
button.addEventListener('click',onClick);
//console.log(options[options.length-1]);
});
function onClick(event){
let order = parseInt(event.currentTarget.getAttribute('order'));
if(order == expected){
expected++;
options[order].clicked = true;
console.log(options[order]);
}
}
<div id="content">
<h1 id="roomNum">Room 2</h1>
<p id="roomInfo">Once again the door seems to magically close behind you.
<br /> Unlike the stone floor from the previous room, this one is divided up into wooden slabs.<br /> You press your foot onto a slab. It slides down, and an arrrow shoots from the roof.<br /> You barely get out of the way but somehow you dodge it.
You tell yourself to watch your step...</p>
<p id="step"></p>
<p id="step2"></p>
<div class="menu-container" id="puzzle">
<div class="button-container">
1
2
3
4
5
6
7
8
9
</div>
</div>
</div>
<br><br>
<div id="death">
Try Again?
</div>
Next Room

Show a loader while waiting for the iframe to load according to the link clicked, and hide the loader after iframe has loaded using AngularJS

I'm trying to show a loader while waiting for the iframe to load according to the link clicked. I use Semantic UI's loader. So far, what it can do is show the loader once the link is clicked. However, the loader will not disappear anymore, even after the iframe document has loaded.
Here is the HTML code:
<div class="drive-link">
<div ng-if = "!READY.value"> <!-- to check if the link has been clicked -->
<div class="ui active centered inline loader"></div>
</div>
<iframe name="embedded-iframe" allowfullscreen="" frameborder="0" iframe-onload></iframe>
</div>
<div class="active content">
<a target="embedded-iframe" href="{{file.link}}" ng-click="show_file_name(file)"> {{file.name}} </a>
<div ng-repeat="next_file in files | limitTo:files.length:$parent.$index">
<a target="embedded-iframe" ng-if="$index > 0 && next_file.category_id == file.category_id" href="{{next_file.link}}" ng-click="show_file_name(next_file)">{{next_file.name}}</a>
</div>
</div>
AngularJS code:
app.controller('mainController', function($scope) {
$scope.READY = {value:true};
$scope.show_file_name = function(file){
$scope.fileName = file.name;
$scope.fileDesc=file.description;
$scope.READY = {value:false};
}
});
app.directive("iframeOnload", function() {
return function(scope) {
scope.READY.value = true;
console.log(scope.READY.value)
};
});
I have a directive to iframe, called iframe-onload. I was thinking that if the anchor tag was clicked, it would somehow connected to the iframe (since clicking the anchor tag would show the embedded document anyway), and it would trigger iframe-onload, which would change READY's value. However, this was not the case, and iframe-onload would only be triggered once, when the HTML page loaded.
Note:
I'm trying to to stay away from timeouts because I don't think hard coding how long the loader will show is the best way to go.
Any help will be very much appreciated. Thank you!
Use simple approach which is that use ng show with your loader code. for example if you have loader in gif image like this
Link To be click
<img src="loader.gif" ng-show="loader"/>
and then in controller you can do like this
$scope.loader=false;
$scope.activateLoader=function(){
$scope.loader=true;
}
this is html table where my data loads.
<tr ng-if="!isDataLoading" ng-repeat="x in companies">
<td>{{x.Id}}</td>
<td>{{x.CompanyName}}</td>
<td>{{x.ContactPerson}}</td>
<td>{{x.TotalRerrals}}</td>
<td>{{TotalRegistered}}</td>
<td>{{x.TotalConverted}}</td>
<td>{{x.TotalSalesAgents}}</td>
<td class="text-green"><i class="fa fa-circle"></i> {{x.AccountStatus}}</td>
</tr>
<div ng-if="isDataLoading" style="width: 100px; margin: auto;">
<img src="assets/loader.gif" style="width: 100px; height: 100px;">
</div>
and here is my controller code
User.getCompanies().success(function(res) {
console.log('All companies', res);
if (res != null || res != "") {
$scope.customers = res;
$scope.companies = [];
for (var i = 0; i < res.length; i++) {
$scope.companies.push({
Id: res[i].Id,
AccountStatus: res[i].AccountStatus,
CompanyName: res[i].CompanyName,
ContactPerson: res[i].ContactPerson,
TotalConverted: res[i].TotalConverted,
TotalRegistered: res[i].TotalRegistered,
TotalRerrals: res[i].TotalRerrals,
TotalSalesAgents: res[i].TotalSalesAgents,
})
}
}
$scope.isDataLoading = false;
})
.error(function(err) {
console.log('error', err);
$scope.isDataLoading = false;
})
You can take this as an example. and change this code according to your need.

HTML5 <audio> Random Audio

i'm back from nowhere.
I have something for school where we need to make a website.
Everyone in my class uses those easy drag 'n drop builders.
I'm ofcourse making it with Notepad++.
So, a 1990 looking page is ofcourse not enough with some fun music.
I have found around 3 to 4 Mario Bros online music to use.
But it only starts the first source link, never the others.
I want to know how to do it, Google doesn't really help.
This is my code:
<audio autoplay="autoplay" controls="controls" title="Radio implented by Rootel">
So my question is, how do I autoplay this list? I didn't give a full list of the music, sorry.
Here you can make it with javascript!
//javascript
var _player = document.getElementById("player"),
_playlist = document.getElementById("playlist"),
_stop = document.getElementById("stop");
// functions
function playlistItemClick(clickedElement) {
var selected = _playlist.querySelector(".selected");
if (selected) {
selected.classList.remove("selected");
}
clickedElement.classList.add("selected");
_player.src = clickedElement.getAttribute("data-ogg");
_player.play();
}
function playNext() {
var selected = _playlist.querySelector("li.selected");
if (selected && selected.nextSibling) {
playlistItemClick(selected.nextSibling);
}
}
// event listeners
_stop.addEventListener("click", function () {
_player.pause();
});
_player.addEventListener("ended", playNext);
_playlist.addEventListener("click", function (e) {
if (e.target && e.target.nodeName === "LI") {
playlistItemClick(e.target);
}
});
.selected {
font-weight: bold;
font-size:20px;
}
<!--html-->
<audio id="player"></audio>
<ul id="playlist"><li data-ogg="http://www.lunerouge.org/sons/sf/LRWeird%201%20by%20Lionel%20Allorge.ogg">Space 1</li><li data-ogg="http://www.lunerouge.org/sons/sf/LRWeird%202%20by%20Lionel%20Allorge.ogg">Space 2</li><li data-ogg="http://www.lunerouge.org/sons/sf/LRWeird%203%20by%20Lionel%20Allorge.ogg">Space Lab</li></ul>
<button id="stop">Stop</button>
hope it helps!!!