Ok so I have multiple elements with the class play-button and I would like to run a function on click. The function should only run once and it should only run on the element which was clicked. However with my current code it runs the function on every element with the same class. I understand why it is doing this but can't think of a solution. Any ideas?
This is my jQuery:
$( ".play-button" ).click(function() {
alert("hello")
});
And this is a sample of the html:
<ul>
<li><button class="play-button">content</li>
<li><button class="play-button">content 2</li>
</ul>
UPDATE - FULL CODE:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<html>
<h1>Uploads</h1>
<ul id="results"></ul>
<iframe src="http://youtube.com/embed/MsGT2CczVTk?controls=0&iv_load_policy=3&rel=0&showinfo=0" width="560" height="315" frameborder="0" allowfullscreen=""></iframe>
</html>
<script>
//playlsit iD: UUtinbF-Q-fVthA0qrFQTgXQ
//api key: AIzaSyBt-q6kHra6D7ZKDv7zRKi458KiiVaKkvE
var channelName = 'caseyneistat';
$(document).ready(function() {
$.get (
"https://www.googleapis.com/youtube/v3/channels", {
part: 'contentDetails',
forUsername: channelName,
key: 'AIzaSyBt-q6kHra6D7ZKDv7zRKi458KiiVaKkvE'},
function (data) {
$.each(data.items, function(i, item) {
console.log(item);
pid = item.contentDetails.relatedPlaylists.uploads;
getVids(pid);
});
}
)
function getVids(pid) {
$.get (
"https://www.googleapis.com/youtube/v3/playlistItems", {
part: 'snippet',
maxResults: 10,
playlistId: pid,
key: 'AIzaSyBt-q6kHra6D7ZKDv7zRKi458KiiVaKkvE'},
function (data) {
var output;
$.each(data.items, function(i, item) {
console.log(item);
videoTitle = item.snippet.title;
videoId = item.snippet.resourceId.videoId;
output = '<li> <span>'+ videoTitle +'</span><br><div class="thumbnail-wrapper"><img src="http://img.youtube.com/vi/'+ videoId+'/mqdefault.jpg" class="thumbnail"><img src="http://www.radiobilly.com/wp-content/themes/radiobilly/img/play-white.png" class="play-button"></div><span id="videoId">'+ videoId +'</span></li>';
// <iframe src="http://youtube.com/embed/'+ videoId +'"></li>';
//Append to results list
$('#results').append(output);
$(".play-button").click(function() {
alert("hello");
$(".play-button").off("click");
});
});
}
)
}
});
</script>
<style>
ul {list-style: none; padding: 0px}
iframe {display: none;}
/* Player Styling */
.thumbnail {
max-width: 100%;
height: auto;
width: 100%;
}
.thumbnail-wrapper {
position: relative;
display: inline-block;
width: 100%;
}
.play-button {
position: absolute;
width: 50px;
height: 50px;
left: 0px;
margin-left: calc(50% - 25px);
margin-right: calc(50% - 25px);
top: calc(50% - 25px);
}
.ytp-chrome-top-buttons {display: none}
</style>