Jquery on off first click doesn't fire on first click


Jquery on off first click doesn't fire on first click



I'm using MVC 5 and Razor front end. When I click any button for the first time, it will not play. It will play on the second click. I tried .off at the end of the code but it didnt work. I want it to play for the first click on a button then turn off. Right now it takes two clicks on a button to start the track and work correctly for the other tracks.


function play() {
//$(".song").unbind().click(function () {
$(".song").off('click').on('click', function () {

//this is the url
var url = $(this).attr("data-song");

var audio = $("#myAudio")[0];

if (audio.paused) {
audio.src = url;
audio.play();
} else {
audio.pause();
audio.currentTime = 0;
}


});



Here is my HTML:


<table class="table" id="trackTable">
<tr>
<th>

</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>

</tr>

@foreach (var item in Model)
{
<tr>
<td class="songRow">
<a href="#" class="song" data-song="@Url.Content(item.Path)" onclick="play()" ><img src="~/Images/playpause.png" alt="playpause" id="playbutton" /></a>

</td>

<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td></td>
</tr>
}







2 Answers
2



Have you tried this?


$(".song").on('click', function () {
$(this).off('click');

// do the other stuff
}



This way your link can be clicked once, and then click event handler is removed.





Tried it and it will not play at all.
– r lo
Jun 30 at 13:56



In this u first used on click function instead of using off click





Still takes two clicks to play.
– r lo
Jun 30 at 13:49






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV