3

Is there equivalent of JS's play() or pause() methods in jQuery ? I'm looking for jquery solutions but preferably no other plug-ins.

$('#play').click(function() { 
    function play() {  
      //  the same in jquery ?  
        document.getElementById('demo').play();
        document.getElementById('demo').volume = 1;       
    }
    function play_pause() { 
       //  the same in jquery ?
        document.getElementById('demo').pause();
        document.getElementById('demo').currentTime = 0;        
    }
    if ( $(this).val() === "play" ) {
       $(this).val("pause"); 
       play();
    } else {
       $(this).val("play");
      pause();
    } 
});

I need the simplest solution, not big fancy plugins please.

Bor
  • 775
  • 3
  • 19
  • 44

1 Answers1

5

You can get the raw HTML element from jQuery like this;

$("#demo")[0].play();

You may also need to check if the demo element actually exists:

if($("#demo").length) $("#demo")[0].play();

So in your example, you would have:

$('#play').click(function() { 
    if ( $(this).val() === "play" ) {
       $(this).val("pause");
       $("#demo")[0].play();
       $("#demo")[0].volume = 1;
    } else {
       $(this).val("play")[0].pause();
       $("#demo")[0].pause();
       $("#demo")[0].currentTime = 0; 
    } 
});
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • Can I use this [0] for a particular instance, when I have say 10 audio tags of different instances ? – Bor Oct 30 '13 at 08:11
  • @Borislav Sure can. If you have 13 audio elements, you can use `$("#audio")[12]` to access the 13th element. Again though, you might want to check that there are *actually* 13 elements before trying to access it. – CodingIntrigue Oct 30 '13 at 08:19
  • I will check it with each() and probably with some kind of [this] – Bor Oct 30 '13 at 08:23
  • If you are using `.each` don't forget that it contains an overload for the DOM element: `$("#audio").each(index, element) { element.play(); // Element is a DOM element, not a jQuery object });` :) – CodingIntrigue Oct 30 '13 at 08:30