banu prakash banu prakash - 12 days ago 5
Javascript Question

Play audio audio file at a time

I have 5 images, each has an audio file that plays when the image is clicked.

I want the audio that is playing for one image to stop when another image is clicked and then play the audio for that image.

$('.cl').click(function() {
var DOMElem = $('.cs').get(0);
DOMElem.paused ? DOMElem.play() : DOMElem.pause();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img class="cl" src="photo/198.jpg" />
</br>
<audio class="cs">
<source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>
<img class="cl" src="photo/198.jpg" />
</br>
<audio class="cs">
<source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>
<img class="cl" src="photo/198.jpg" />
</br>
<audio class="cs">
<source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>

Answer

You are getting first audio object every time. You need to get the object with respect to img

$('.cl').click(function () {
   var DOMElem = $(this).next().next().get(0);
   DOMElem.paused ? DOMElem.play() : DOMElem.pause();
});

A better approach is to make a container div for each image and audio and when you click the image you can get the audio object with respect to container.

<div class="audioContainer">
        <img class="cl" src="photo/198.jpg" />
        </br>
        <audio class="cs">
            <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
        </audio>
    </div>
    <div class="audioContainer">
        <img class="cl" src="photo/198.jpg" />
        </br>
        <audio class="cs">
            <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
        </audio>
    </div>
    <div class="audioContainer">
        <img class="cl" src="photo/198.jpg" />
        </br>
        <audio class="cs">
            <source src="http://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
        </audio>
    </div>
    <script>

         var DOMElem;
    $('.cl').click(function () {
        if (DOMElem) {
            if (!DOMElem.paused)
                DOMElem.pause();
        }
        DOMElem = $(this).parent().find('.cs').get(0);
        DOMElem.play();
        console.log(DOMElem);
    });
    </script>
Comments