Play all audio elements on a HTML page using Javascript - javascript

So I have a button that you can click to play every single audio element on the page, but they way it does it is not very good, it uses getElementById for every single element. My page has many audio elements and more are getting added, so I want to get this over with before this problem gets out of hand.
document.getElementById("sound1").play();
document.getElementById("sound2").play();
document.getElementById("sound3").play();
document.getElementById("sound4").play();
document.getElementById("sound5").play();
document.getElementById("sound6").play();
// more code here: https://github.com/3kh0/3kh0.github.io/blob/main/projects/soundboard/index.html
I can use jQuery, but I am trying not to, so a plain JavaScript solution would be nice.

As per your question of targeting all audio elements on a page, the following code will do that for you :
// create a HTMLCollection of audio elements in constant els
const els = document.getElementsByTagName("AUDIO");
// use Array.from() method to convert els to array,
// then iterate over it
Array.from(els).forEach((el) => {
el.play();
});
The same functionality could also be used to only play select groups of audio elements. One could use class names for this purpose, or data-attributes.
For example, all audio elements created like this ...
<audio controls class="group-one" data-group="one">
<source src="file.mp3" type="audio/mpeg">
</audio>
... could then be added to the HTMLCollection (in the case of getElementsByClassName) or NodeList (when using querySelectorAll) like this ...
const els = document.getElementsByClassName("group-one");
// OR
const els = document.querySelectorAll('audio[data-group="one"]');

Related

Using Javascript to Change HTML sound

I would like to change the audio element I inserted with another audio element.
I checked the solution at: Create Audio element dynamically in Javascript, and I don't understand why my code isn't working.
In HTML I have:
<audio id="sound" src="shush1.mp3" controls>
Your Browser Does Not Support the Audio Feature
</audio>
and in babySounds.js I have:
var sound = document.createElement('audio');
sound.src = "Shush2.mp3";
sound.controls = "controls";
document.getElementById("sound").appendChild(sound);
Your code attempts to append your new audio element as a child of the one that's already there (appendChild), rather than replacing it.
If you want to replace it, you can use the replaceWith method instead in all non-obsolete browsers:
const sound = /*...*/;
document.getElementById("sound").replaceWith(sound);`
But if you just want to change what the sound is, you can assign to the existing element's src property instead, there's no need to create a whole new element:
document.getElementById("sound").src = "Shush2.mp3";
From the spec:
If a src attribute of a media element is set or changed, the user agent must invoke the media element's media element load algorithm.
...
The src IDL attribute on media elements must reflect the content attribute of the same name.

add a class to randomly selected tags in javascript

I have stored 5 random custom tag elements named logocon from the DOM. I want to add a class to each of those randomly selected tags only. here is the code that gets 5 random tags. I tried .addClass() but it does not work.
randomElements = jQuery("logocon").get().sort(function(){
return Math.round(Math.random())-0.5
}).slice(0,5)
randomElements is an array of DOM elements, not a jQuery collection. You can wrap it with $() to convert it to a jQuery collection so you can use .addClass().
$(randomElements).addClass('newclass');

adding onclick event on class

I am trying to write a greasemonkey script which adds an onClick listener on a button (define below) and do some specific things. I was trying to get this button obj using document.getElementsByTagName but it returned null. I tried to iterate over document.anchors and it returned null as well. how can i get this element object and add onclick event to it.
<a class="editicon" aria-label="Edit this field" role="button" href="#"><img src="https://url-to/images/edit.png?3423434"></a>
There is already an onclick added to this object, I don't want to replace it.
UPDATE
Adding my Greasemonkey script
// ==UserScript==
// #name cr
// #namespace my_namespace
// #version 1
// #grant none
// ==/UserScript==
(function(){
console.log('test ...')
var editicon = document.getElementsByTagName('editicon');
console.log(editicon);
})();
First, your question talks about a button, but your code does not include one. Instead of using an <a> element and then disabling its native navigation function with href="#", it would be semantically better to use an actual <button> element.
Second, you should not use inline HTML event attributes (onclick, onmouseover, etc.) as they:
Create "spaghetti code" that doesn't scale, is hard to read, leads to duplication and doesn't follow the "separation of concerns" methodology.
Create global anonymous wrapper functions around your event attribute value that alter the this binding of your code.
Don't follow the W3C Event Standard of using the addEventListener() API.
Now, there are several ways to get a reference to a DOM element and some are better than others depending on your HTML structure and how many elements you are trying to get. document.getElementsByTagName() returns a "node list" of all the elements that were found. Even if no elements were found, you still get this list as the returned object (the list will just be empty when no elements were found). To extract a particular element from the result, you'll need to pass an index into that list, which is an "array-like" object. Additionally, getElementsByTagName returns a "live" node list, meaning that it will re-scan the document upon every interaction to ensure that the most current list is provided. While this can be beneficial in some circumstances, it comes with a performance cost.
This, for example, would extract the first a element in the document:
var myElement = document.getElementsByTagName("a")[0];
But, since you are only expecting a single element, that is overkill. To get just one element, and if that element has an id attribute on it, you can/should use: document.getElementById("theIdHere"); as getElementById() is generally the fastest way to find a single element in your HTML structure.
Additionally, there are other ways to get an element or elements, like querySelector() and querySelectorAll(), which allow you to use CSS selector syntax in your JavaScript queries.
For your code, see the following snippet:
// Get a reference to the first <button> element in the document
var b = document.querySelector("button");
// Or, if the element has an id, the best solution would be:
var b = document.getElementById("btn");
// Add a click event handler to the element
b.addEventListener("click", handleClick);
// Function that will be called when anchor is clicked
function handleClick(){
alert("You clicked me!");
}
button { background-color:rgba(0,0,0,0); }
img { width: 50px; }
<button class="editicon" aria-label="Edit this field" role="button" id="btn"><img src="https://s-media-cache-ak0.pinimg.com/736x/5a/42/c6/5a42c6224e3ce7fa9837965270bfcdd9--smiley-face-images-smiley-faces.jpg"></button>

Need to find video in dom

I need to find if the DOM contains video or not. I want to find video irrespective of what way it is inserted in DOM.
I tried phantomJS but did not get any comprehensive way k
You can try this :-
$(document).ready(function(){
if($('video').length){ //search for any video tag inside DOM
alert("here"); // do whatever you want here
}
});

Is it possible to select elements by id like in jQuery?

Currently i selecting elements like jQuery('a#encode-url-button, a#decode-url-button'), is it possible without creating a new function select the same elements in pure js ? Something like document.getElementById('encode-url-button, decode-url-button').onclick = function... ?
Yes, with document.querySelectorAll. It accepts a CSS selector. Most modern browsers support it.
If you really need to support IE7 and earlier, then of course you can just do two getElementById calls and throw away the elements if they're not anchors. (Which is what the selector a#someid does.)
If you're going to operate on the elements, you need to loop through the resulting list from querySelectorAll, since the DOM API doesn't have the "set theory" orientation that jQuery has. So for instance:
var list = document.querySelectorAll("#encode-url-button, #decode-url-button");
var index;
for (index = 0; index < list.length; ++index) {
list[index].onclick = clickhandler;
}
function clickHandler() {
// ....
}
(I don't advocate using DOM0 handlers like that, look at using addEventListener instead, but as you quoted onclick in the question...)
FWIW, 99.99% of the time, it makes no sense to combine an id selector with a tag selector (a#someid), since id values are unique. Just #someid is usually better. Adding the tag to it doesn't make anything faster; in fact, it makes things slower. The only reason for doing it is if sometimes the element will have one tag (say, a), sometimes another (say, I dunno, div), and you only want to get it if it has one but not the other. Very edge case...

Categories

Resources