javascript - Cant stop audio on click -


i have problem stoping audio player on click. player starts im unable stop when click again. can please me ? here code:

$(".portfolio-listen").click(function(e) {   e.preventdefault();   var audiourl = $(this).attr("href");   var audioelement = document.createelement("audio");   audioelement.setattribute('src', audiourl);   $(this).toggleclass("playing");    if ($(this).hasclass("playing")) {     audioelement.play();   } else {     audioelement.pause();   }   }); 

this example more complex if wish load new audio source depending on button clicked, make audio element global , check if it's defined proceed toggling audio play/pause.

// demo purpose, use var audiourl = $(this).href('href')  var audiourl = 'https://allthingsaudio.wikispaces.com/file/view/shuffle%20for%20k.m.mp3/139190697/shuffle%20for%20k.m.mp3';    // make audioelement global  var audioelement;      $(".portfolio-listen").click(function(e) {      e.preventdefault();       if(!audioelement){        audioelement = document.createelement("audio");        audioelement.setattribute('src', audiourl);    }        $(this).toggleclass("playing");        if ($(this).hasclass("playing")) {      audioelement.play();    } else {      audioelement.pause();    }      });
button {     background: #e91e63;  }  button.playing {     background: #8bc34a;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>  <button class="portfolio-listen">play</button>


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -