play/pause Audio on Mousedown/up with jQuery - javascript

I am trying to use jQuery to dynamically assign listeners to anchors to play sound on mousedown and pause on mouseup. Here's my html:
<p>Meet
<a class="easter-egg">Buck
<audio class="egg-aud" src="file.mp3">
<source src="file.ogg" />
</audio>
<img class="egg-img" alt="" src="file.jpg" />
</a>.
</p>
And my js:
$( "a.easter-egg" ).mousedown( function() {
$( this ).find( "audio.egg-aud" )[0].play();
});
$( "a.easter-egg" ).mouseup( function() {
var audio = $( this ).find( "audio.egg-aud" )[0];
audio.pause();
audio.currentTime = 0;
});
EDIT: In jsfiddle my code works perfectly until I wrap the <p> in a <div class="entry-content">, at which point it breaks. I pasted a sample of my website into jsfiddle, where you can try deleting the div and see that it works without it.

Problem:
You were trying to set currentTime of audio tag that has been appended dynamically. Thus, you have to wait for audio tag to be ready to play.
Solution:
Check whether the audio element is ready to be played using the canplay event.
// When the audio element "can"be"play"ed, fire the function.
audio.addEventListener("canplay", function() {
this.currentTime = 0;
},true);
Comments:
Previously, the error you had been getting in the console was:
"Error: An attempt was made to use an object that is not, or is no longer, usable."
Do keep checking the errors, they are very useful :)
The same thing applies for <video> tags that have been appended dynamically.
Live Demo
Hope that helps !

Aaaaand right after I went to bed I realized the problem. I recently wrote a script that changes the text of each instance of an author's name into a link to their list of posts. To do this it replaces the contents of each p element with a new string, which means it recreates the anchors and audios that I'm working with. So ill i guess ill just have to make sure that happens first.

Related

jQuery video on ended for numerous videos

I am showing a couple a number of videos in succession.
When the first video finishes I ask the user a question and then show another video following their response. After the second video I ask the user a final question.
The problem is that when the second video ends both .question-one and .question-two are displayed as a block again, as it appears the code from the first on('ended..) method is being triggered again.
I tried to use unbind to remove the binding from the videos, but this didn't work.
Here is my code below.
HTML
<video>
<source src="1.mp4" type="video/mp4">
</video>
JS
$('.video-one').bind('ended',function(){
$(this).removeClass('video-one');
$(this).addClass('video-two');
$('#video-background').css('display', 'none');
$('.question-one').fadeIn('slow');
$('.video-one').unbind('ended');
});
$('.question-one').click(function(){
$('.question-one').css('display', 'none');
$('#video-background').css('display', 'block');
$('video').attr('src', '2.mp4');
});
$('.video-two').bind('ended',function(){
$(this).removeClass('video-two');
$(this).addClass('video-three');
$('#video-background').css('display', 'none');
$('.question-two').fadeIn('slow');
$('.video-two').unbind('ended');
});
Is there something else that I am missing?
instead of changing order of instructions like #Offbeatmammal said, I would suggest unbinding event based on ID of element, because you want to unbind only this one, specific - not everyone with this class probably. it's only semantic reason. you would then have to add an event parameter to your function, and get id by event.target.id if I remember well.

Play multiple videos on page with jQuery each() function

I have a page with multiple HTML5 videos on it. For each video, there is a "poster" image that sits on top of the video. When someone clicks the poster image, the image disappears via CSS, and the video below it plays.
My problem is that I can only get the FIRST video on the page to play when someone clicks it. I'd like the user to be able to click any of the videos on the page to play them. My guess is that I somehow need to incorporate the "each()" function into the jQuery code.
Here is my current jQuery code:
$('#videocover').click(function() {
var video = $('#wp_mep_1').get(0);
video.play();
$(this).css('visibility', 'hidden');
return false;
});
Below is a JSFiddle with multiple videos on the page, but only the first one working when you click it. Feel free to play around:
https://jsfiddle.net/rtkarpeles/ammebd3k/3/
Thanks in advance for any and all help you can provide!
You cannot have multiple elements with same ID. Change them to class.
Change the video-container from ID to class and videocover as well.
<div class="video-container">
<video>...</video>
<div class="videocover"></div>
</div>
With the above structure the below script should work fine.
$('.videocover').click(function () {
var video = $(this).closest('.video-container').find('video')[0];
video.play();
$(this).css('visibility', 'hidden');
return false;
});
.closest() will fetch the first match when traversing through ancestors in DOM
Here is a demo https://jsfiddle.net/dhirajbodicherla/ammebd3k/5/
Change your IDs to classes.
https://jsfiddle.net/ammebd3k/6/
.videocover and .wmp_mep_1
IDs must be unique on a page, or else you run into exactly your issue.

changing src and currentTime doesn't work together

Well, the thing is, for my application, I have to change the video src and currentTime dynamically. I have tried changing both independently which worked fine. But, when I tried to do them together, there is some problem.
This is my video tag and a button, onclicking which src and currentTime must be changed.
<video id="video" src="sample.mp3" controls autoplay></video>
<button onclick="foobar()">change</button>
and my foobar() function is
function foobar()
{
v=document.getElementById("video");
v.src = "foo.mp3";
v.load();
v.currentTime = 3;
}
When I remove either v.src or v.currentTime, its working fine...
I have tried using networkState and currentState, no luck. I have even waited for some time(javascript timers) made sure that the new mp3 file is completely loaded and then tried changing currentTime. Even that did not work.
Please help me..
PS: I don't want to use any third party libraries.
You have to change the currentTime when the video is ready for that. In order to do that you can listen for a event from the video and change then the property, for example the loadeddata event. You can see the full list here.
v.addEventListener('loadeddata', function(){v.currentTime = 3;}, true);
You may use the url to set the timer:
function foobar()
{
v=document.getElementById("video");
v.src = "foo.mp3#t=3";
v.load();
}
It works in this fiddle http://jsfiddle.net/UkZLf/

How do I play a sound on Image-Click in HTML?

I'm trying to play a sound when i click or hover over my play button? Here's what i have so far. I have a button, if i hover over it it changes the Image, now i also want it to play an mp3.
play a {
position:relative;
float:left;
width:155px;
height:134px;
background-image:url(../images/Goodsound_PLAY_UP.png);
}
play a:hover {
background-image:url(../images/Goodsound_PLAY_P.png);
I want to play a sound here
}
Im sorry for asking such an easy question. I'm an html noob, started last week.
It's not that easy to play a sound in HTML. In fact, it wasn't until the html5 audio was there ! Even if html5 is not supported everywhere, it's now a little bit easier to play a sound in the browser.
My advice is to use mediaelementJS, a javascript library that fills the gap between old browser and html5 audio (and video) spec. Do not use the player (that comes with a full control bar), but use only the mediaelementjs component. To use it, simply include the library in the head of your page
<script src="js/libs/mediaelement.min.js"></script>
First, you have to put an audio tag in your html :
<audio id="mySound" src="my_audio_file.mp3" type="audio/mpeg"></audio>
Then, call the Mediaelement library
var mySound = new MediaElement('mySound');
Finally, play it on your click or over event (here I use jQuery)
$('.play a').mouseover(function(){ mySound.play() });
You can use this:
JavaScript
var audio = $("#audio");
$("play a").mouseenter( function() {
audio.play();
}
where audio is an <audio> element, and play a is element which is hover.
Using jQuery:
$("object_element_id") .on ('mouseover', function(e){
// audio play code here
});
$("object_element_id") .on ('mouseout', function(e){
// audio pause/stop code here
});
Why "on"? Just imagine a "AJAX page refresh". For remove it:
$("object_element_id") .off ('mouseenter');
Why "mouseover" and "mouseout"? Maybe you want to add extra functions for each status, like change IMG SRC of the button, make some effects... feel free. And why the "e" element? The E element is the object who fired the event - the image, the link etc. Do everything with it (or just remove it).
For audio play, you can use HTML5 tags. It's easy and are supported by the major browsers (you didn't asked "retrocompatibility") You can cache the element (like Mateusz' answer) and use it:
var $audio = $("#audio_element_id"); //for cache the element
$audio.setAttribute('src', url_link); //for change the URL file (ir can be MP3, OGG...)
$audio.play(); //for the mouseover
$audio.stop(); //for the mouseout
Then, the final code:
var $audio = $("audio_element"); //caching
$("object_element_id") .on ('mouseover', function(e){
$audio.play();
});
$("object_element_id") .on ('mouseout', function(e){
$audio.stop();
});
You might also find this code useful (I think it is fairly modern, so it might not work with old browsers; I use it with Firefox 32).
<audio controls> <source src="song.mp3" type="audio/mpeg"> </audio>
There is a similar one for video, too:
<video width="320" height="240" controls> <source src="clip.mp4" type="video/mp4"> </video>

Jquery return original event on video

I have multiple video plays on a single page which I need to listen for onplay and onpause triggers, and execute custom functions which take the IDs from each of the videos tags. I need to be able to get the video id that was activated. Ive tried a few different ways, with the simple vid.onplay event works well when I know what ID is being called into. I've tried the $("video").onplay but doesn't seem to be working.
jQuery( document ).ready(function($) {
$("video").onplay = function() {
alert("The video has been paused");
};
var vid = document.getElementbyid("myVideo");
vid.onplay = function() {
alert("The video has been played");
};
});
<video class="mdia_video_player" id=myVideo poster="https://tcokchallenge.com/launch2/wp-content/uploads/2020/04/Carter.jpg?336660464" id="v0" onclick="doplayvideo(" 0")"="" controls="">
<source src="https://tcokchallenge.com/launch2/wp-content/uploads/2020/04/Carter.mp4?1222152426" type="video/mp4">
</video>```
In your first demo, it should be $("#video") to call by ID. It also says .onplay and then says that is was paused so you might want to fix that.
Ended up doing a much simpler answer, videos are within a php loop. So, I placed this within the tag
onpause="dopausevideo(<?=$vid ?>)"
onplay="doplayvideo(<?=$vid ?>)"

Categories