Play/Pause Audio Button Using HTML5 And JavaScript - javascript

I am facing a problem for a couple of hours. I have some Radio Channels into a HTML document. Every channel has an image (it's logo). I can't figure out how to make the "click to Play/Pause" working.
Here's the JSFiddle document : http://jsfiddle.net/s35vk80m/1/ 123
If you click on the first image, it will play/pause the channel. The second button act like the first one.
How can I make it work, so that both of them would work independently and if I click on the second one while the first one is running, it would stop the first channel and start the second one?
I am sorry, I am a begginer :-).

Based on w3schools html5 audio, m3 and pls audio types are not supported.
Maybe streaming will do (never tried), something like this is-it-possible-to-play-shoutcast-internet-radio-streams-with-html5.

function aud_play_pause() is defined in your code twice. You need to give the second function a different name or just use one function to do both things. I would do something like this:
function aud_play_pause(channel) {
var Radio21 = document.getElementById("Radio21");
var RadioZU = document.getElementById("RadioZU");
if(channel == 'radio21'){
RadioZU.pause();
if (Radio21.paused) {
Radio21.play();
} else {
Radio21.pause();
}
}
if(channel == 'radioZU'){
Radio21.pause();
if (RadioZU.paused) {
RadioZU.play();
} else {
RadioZU.pause();
}
}
}
</script>
Someone more knowledgeable than I could probably provide a more elegant solution but this should work.
Also, I couldn't get your JSFiddle to work in my browser and I couldn't get my JSFiddle to work so I haven't been able to test the function. Firefox didn't like the ContentTypes you are using: "HTTP "Content-Type" of "audio/x-mpegurl" is not supported. Load of media resource http://www.radio21.ro/Radio21Live.m3u failed."
EDIT:
I thought about this a little more and basically you need a toggle. I can't get your example to work in Firefox so I'm going to create a toggle example that doesn't solve your problem but should illustrate how to fix it.
function example(string) {
var first_div = document.getElementById("one");
var second_div = document.getElementById("two");
if(string == 'one'){
second_div.innerHTML = "OFF";
if (first_div.innerHTML == "OFF") {
first_div.innerHTML = "ON";
} else {
first_div.innerHTML = "OFF";
}
}
if(string == 'two'){
first_div.innerHTML = "OFF";
if (second_div.innerHTML == "OFF") {
second_div.innerHTML = "ON";
} else {
second_div.innerHTML = "OFF";
}
}
}
<div id="one" onclick="example('one')">OFF</div>
<div id="two" onclick="example('two')">OFF</div>

Related

Double tap/click ruining JS memory game

When user-testing a memory game with my 4-year-old, she discovered a bug. When you double-tap on a card it considers it a match. I tried to disable the that had been clicked using this.style.pointerEvents = 'none' then setting it back to auto.
This works for the second clicked card but not the first (defeating the point of using it and creating a new bug! The project is currently deployed at: https://dandavies23.github.io/smoothie-moves/
If you’ve any ideas on how I could do this better greatly appreciated!
function tumblerLift() {
let cardId = this.getAttribute('data-id')
this.style.pointerEvents = 'none';
cardsChosen.push(fruitVegArray[cardId].name)
cardsChosenId.push(cardId)
this.setAttribute('src', fruitVegArray[cardId].img)
console.log(fruitVegArray[cardId])
if (cardsChosen.length === 2) {
setTimeout(checkForMatch, 500)
this.style.pointerEvents = 'auto';
}
} ```
Well, I guess you can try using another if statement like this(based on your setAttribute)
function tumblerLift() {
let cardId = this.getAttribute('data-id')
this.style.pointerEvents = 'none';
cardsChosen.push(fruitVegArray[cardId].name)
cardsChosenId.push(cardId)
if(this.src==fruitVegArray[cardId].img){return null} //image already chosen
this.setAttribute('src', fruitVegArray[cardId].img)
console.log(fruitVegArray[cardId])
if (cardsChosen.length === 2) {
setTimeout(checkForMatch, 500)
this.style.pointerEvents = 'auto';
}
}
Thanks to an answer by The Bomb Squad, the null solution helped fix another bug of fruit appearing after they had been matched.
Here is the code I have now:
// Tumbler lift
function tumblerLift() {
if (this.src.includes('images/blank.png')) {
return null
} // prevents fruit from reappearing, credit Y0urs Truly from Github for helping fix this bug
It's feeling a lot more together now; the actual game can be played here: https://dandavies23.github.io/smoothie-moves/

Ideas for a correct function on my webpage?

I am having problems with a javascript function. I want to replace an icon by changing the class.
On my page, I have the following element:
<i class="wait icon" alt="{webui_botstatenotavailable}" title="{webui_botstatenotavailable}" id="{botname}"></i>
The following javascript should change the class, but it does not work:
function incomingBotStatusList(http_request, statusOff, statusOn)
{
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
if (http_request.responseText.length < 7)
{
// Error
}
else
{
var botStatusList = JSON.parse(http_request.responseText);
for (var key in botStatusList)
{
if (botStatusList.hasOwnProperty(key))
{
var botStatusImage = document.getElementById(key);
if (botStatusImage != null)
{
if (botStatusList[key] == 0)
{
botStatusImage.class.innerHTML = "images/bullet_red.png";
botStatusImage.title = statusOff;
botStatusImage.alt = statusOff;
}
else if (botStatusList[key] == 1)
{
botStatusImage.class.innerHTML = "<i class=\"checkmark green icon\">";
botStatusImage.alt = statusOn;
botStatusImage.title = statusOn;
}
}
}
}
}
}
}
}
Did someone from you know how it will work?
Thanks for your help!
Best Regards
Pierre
I see a couple of problems with your code. First, the <i> element is used to apply italic formatting to text. It is not the HTML code for an icon or an image.
Secondly, you write botStatusImage.class.innerHTML, but the Element.class does not exist, and Element.className is a string. It does not have an innerHTML attribute. So, you could write botStatusImage.className = "new_class_name"; and this would be more correct.
You should then change the image source by calling botStatusImage.setAttribute('src', new_url), where you have set new_url to the new image location.
Check out the javascript reference for the Element class that is returned from document.getElementById: check this link
My recommendation, start simple, then make it complex.
First, try to get the icon to change without the AJAX request. Try writing a function like this:
function changeIcon( imageId, newUrl ){
var element = document.getElementById( imageId );
element.setAttribute( "src", newUrl );
}
Then test this function in the console by passing calling it with the URL's manually.
Once that works, don't change it! Next add the AJAX call, and when you have the Icon url from your server response, all you do is call the function that you already wrote and tested. That way you separate the AJAX code from the image update code and you can test them separately.
The key is smaller functions. Build the easy stuff first, and then call those easy functions from the harder functions. Once you know the easy function works well, it becomes much easier to find problems in the harder functions.

Is it possible to use transitions with display none to display block

I'm still developing a genius forum for my website. I want to add some fancy javascript effects. I don't want to use jQuery for now.
My problem is the following: I have an element which appears by checking if the value of the function is true or false. With those check my article shows or hides.
My question is: Is it possible to use transitions so that my block drops down like the way transitions do?
The first js function describes the check and the next function hides or show my article when the values are not empty.
function CheckEmptyValues() {
var inputFields = document.getElementsByTagName('input');
var textFields = document.getElementsByTagName('textarea');
var postData = [inputFields, textFields];
for(var i=0; i<postData.length; i++) {
for(var j=0; j<postData[i].length; j++) {
if(postData[i][j].value !== '') {
return false;
}
}
}
return true;
}
function showPreview() {
if (CheckEmptyValues() === false) {
this.prevPost.style.display = "block";
}
else {
this.prevPost.style.display = "none";
}
}
When my emptyvalues are false the article appears and if not, it disappears. But when this happens you see only show or hide, no further effect or something.
I want to make this something like this effect: http://www.w3schools.com/css/tryit.asp?filename=trycss3_transition1
The height value should start with 0 and end with 150 height or something like that.
Does anyone have a solution how to make this look cool?
Thanks in advance.
No, you can't, display is defined as non animatable.
If you want workarounds, see CSS3 Animation and Display None.
No, display doesn't come in transition-property. But, you can try opacity and for the display:block , put it in your div:hover or only div css.
You could use opacity, and set it to 0 or 1:
this.prevPost.style.display = "block";
this.prevPost.style.opacity = 1;

getElementById not working within if statement - Troubleshooting

I have a simple JS script to swap out elements containing Flash and replace them with other formats for users who don't have Flash installed.
var hideclass="hidden"
var showclass="empty"
function flashFixMain(){
if (swfobject.hasFlashPlayerVersion("7.0.0")) {
document.getElementById('logoflash').className=showclass;
document.getElementById('logononflash').className=hideclass;
} else {
document.getElementById('logoflash').className=hideclass;
document.getElementById('logononflash').className=showclass;
}
}
And put simply, it doesn't work.
The if statement works fine - putting an alert in the appropriate place pops up fine.
I've checked the source of the appropriate page(s) online, and the element name pops up exactly as written (and only once!).
The class names work fine, as they are used as defaults on the page at the start.
So does anyone have any ideas what I might have missed?
change
document.getElementById('logoflash').class=showclass;
to
document.getElementById('logoflash').className = showclass;
it's className, not class
Instead of using .class you need to use the .className property; for instance:
document.getElementById('logoflash').className = showclass;
In modern browsers you can also use .classList to add a class rather than replace all existing classes:
document.getElementById('logoflash').classList.add(showclass);
As an aside, you could consider moving a few statements around like this:
var hasFlash = swfobject.hasFlashPlayerVersion("7.0.0"),
logoFlash = document.getElementById('logoflash'),
logoNonFlash = document.getElementById('logononflash');
logoFlash.className = hasFlash ? showclass : hideclass;
logoNonFlash.className = hasFlash ? hideclass : showclass;
I wrote up a quick test scenario and without seeing more of your environment, do not see anything that should keep this from working as expected.
The one thing I did notice while doing a write up w/o using jQuery (which I guess you are NOT using?) is that your 'addClass' is really a 'REPLACE' class value. You are simply setting it to a single class.
This makes me think, not having seen your environment, that some OTHER classes might be already assigned to your elements that are getting wiped out. This could be causing unexpected behaviour if some of your display is dependent on these other classes...
Without seeing more of your scenario, that is the only thing that seems like it might be an issue.
Anyway, here is my test setup. You might find something in this useful.
<div id="logoflash" class='something'>
Logoflash
</div>
<div id="logononflash" class='else' >
logononflash
</div>
<script>
var swfobject = {FlashPlayerVersion: '7.0.1', hasFlashPlayerVersion: function(v) {if(v == this.FlashPlayerVersion) return true; else return false;}, myName: 'fakeSWObject' };
console.log(swfobject)
var hideclass = "hidden"
var showclass = "empty"
var getById = function(sID) { return document.getElementById(sID); };
var addClass = function(sID, sClass) { getById(sID).className += ' ' + sClass };
function toggleEl(sID, bState){
console.log('begin toggleEl')
console.log('bState: ' + bState)
try {
if(bState == undefined) {
console.log('Toggling by element state');
getById(sID).style.display = getById(sID).style.display == 'none' ? 'block' : 'none';
} else {
console.log('Toggling by argument');
getById(sID).style.display = !!bState ? 'block' : 'none';
}
} catch (err) {
console.log(err);
}
}
function flashFixMain(){
if (swfobject.hasFlashPlayerVersion("7.0.0")) {
console.log('Is Flash 7.0.0');
toggleEl('logoflash', true);
toggleEl('logononflash', false);
addClass('logoflash', hideclass);
addClass('logononflash', showclass);
} else {
console.log('Is NOT Flash 7.0.0');
toggleEl('logoflash', true)
toggleEl('logononflash', false)
addClass('logoflash', showclass);
addClass('logononflash', hideclass);
}
}
$(function(){ // Yes, this is jQuery to fire after doc is ready
flashFixMain();
})
</script>
use Jquery:
$("#logoflash").addClass(hideclass);
or
$('#logoflash').toggleClass(hideclass, swfobject.hasFlashPlayerVersion("7.0.0"));

display message javascript while a calculation is being made

I have been looking around and I cannot seem to figure out how to do this, although it seems like it would be very simple.(mobile development)
What I am trying to do is display a message (kind of like an alert, but not an alert, more like a dialog) while a calculation is being made. Simply like a Loading please wait. I want the message to appear and stay there while the calculation is being done and then be removed. I just cannot seem to find a proper way of doing this.
The submit button is pressed and first checks to make sure all the forms are filled out then it should show the message, it does the calculation, then hides the message.
Here is the Calculation function.
function scpdResults(form) {
//call all of the "choice" functions here
//otherwise, when the page is refreshed, the pulldown might not match the variable
//this shouldn't be a problem, but this is the defensive way to code it
choiceVoltage(form);
choiceMotorRatingVal(form);
getMotorRatingType();
getProduct();
getConnection();
getDisconnect();
getDisclaimer();
getMotorType();
//restore these fields to their default values every time submit is clicked
//this puts the results table into a known state
//it is also used in error checking in the populateResults function
document.getElementById('results').innerHTML = "Results:";
document.getElementById('fuse_cb_sel').innerHTML = "Fuse/CB 1:";
document.getElementById('fuse_cb_sel_2').innerHTML = "Fuse/CB 2:";
document.getElementById('fuse_cb_result').innerHTML = "(result1)";
document.getElementById('fuse_cb_res_2').innerHTML = "(result2)";
document.getElementById('sccr_2').innerHTML = "<b>Fault Rating:</b>";
document.getElementById('sccr_result').innerHTML = "(result)";
document.getElementById('sccr_result_2').innerHTML = "(result)";
document.getElementById('contactor_result').innerHTML = "(result)";
document.getElementById('controller_result').innerHTML = "(result)";
//Make sure something has been selected for each variable
if (product === "Choose an Option." || product === "") {
alert("You must select a value for every field. Select a Value for Product");
**************BLAH************
} else {
//valid entries, so jump to results table
document.location.href = '#results_a';
******This is where the message should start being displayed***********
document.getElementById('motor_result').innerHTML = motorRatingVal + " " + motorRatingType;
document.getElementById('voltage_res_2').innerHTML = voltage + " V";
document.getElementById('product_res_2').innerHTML = product;
document.getElementById('connection_res_2').innerHTML = connection;
document.getElementById('disconnect_res_2').innerHTML = disconnect;
if (BLAH) {
}
else {
}
populateResults();
document.getElementById('CalculatedResults').style.display = "block";
} //end massive else statement that ensures all fields have values
*****Close out of the Loading message********
} //scpd results
Thank you all for your time, it is greatly appreciated
It is a good idea to separate your display code from the calculation code. It should roughly look like this
displayDialog();
makeCalculation();
closeDialog();
If you are having trouble with any of those steps, please add it to your question.
Computers are fast. Really fast. Most modern computers can do several billion instructions per second. Therefore, I'm fairly certain you can rely on a a setTimeout function to fire around 1000ms to be sufficient to show a loading message.
if (product === "Choose an Option." || product === "") {
/* ... */
} else {
/* ... */
var loader = document.getElementById('loader');
loader.style.display = 'block';
window.setTimeout(function() {
loader.style.display = 'none';
document.getElementById('CalculatedResults').style.display = "block";
}, 1000);
}
<div id="loader" style="display: none;">Please wait while we calculate.</div>
You need to give the UI main thread a chance to render your message before starting your calculation.
This is often done like this:
showMessage();
setTimeout(function() {
doCalculation();
cleanUp()
}, 0);
Using the timer allows the code to fall through into the event loop, update the UI, and then start up the calculation.
You're already using a section to pop up a "results" page -- why not pop up a "calculating" page?
Really, there are 4,000,000 different ways of tackling this problem, but why not try writing a "displayCalculatingMessage" function and a "removeCalculatingMessage" function, if you don't want to get all object-oriented on such a simple thing.
function displayCalculatingMessage () {
var submit_button = getSubmitButton();
submit_button.disabled = true;
// optionally get all inputs and disable those, as well
// now, you can either do something like pop up another hidden div,
// that has the loading message in it...
// or you could do something like:
var loading_span = document.createElement("span");
loading_span.id = "loading-message";
loading_span.innerText = "working...";
submit_button.parentElement.replaceChild(loading_span, submit_button);
}
function removeCalculatingMessage () {
var submit_button = getSubmitButton(),
loading_span = document.getElementById("loading-message");
submit_button.disabled = false;
loading_span.parentElement.replaceChild(submit_button, loading_span);
// and then reenable any other disabled elements, et cetera.
// then bring up your results div...
// ...or bring up your results div and do this after
}
There are a billion ways of accomplishing this, it all comes down to how you want it to appear to the user -- WHAT you want to have happen.

Categories