0

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>
7
  • Have you tried using IDs? Commented Jun 27, 2016 at 19:25
  • Use ids, each element should have an id Commented Jun 27, 2016 at 19:25
  • I would have done this but elements are populated with JSON Commented Jun 27, 2016 at 19:25
  • What exactly is your question? You understand why it is doing it but you can't come up with a solution? Commented Jun 27, 2016 at 19:26
  • @dwinnbrown Yes so, what is your question? Commented Jun 27, 2016 at 19:26

2 Answers 2

3

You can use the .off() method to remove the binding after the first click:

$(".play-button").click(function() {
  alert("hello");
  $(".play-button").off("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li><button class="play-button">content</button></li>
<li><button class="play-button">content 2</button></li>
</ul>

Sign up to request clarification or add additional context in comments.

1 Comment

it continues to run with the syntax i am using. I will post the full code see updated question
1

It is only running once, and running on the element you actually click. Your markup is missing the close tags for the buttons but if you alert the button's html you can see it working.

Fiddle

<ul>
<li><button class="play-button">content</button></li>
<li><button class="play-button">content 2</button></li>
</ul>

$( ".play-button" ).click(function() {
       alert($(this).html());
});

3 Comments

Good catch, I didn't see that until you mentioned it. My guess is that since there is no closing </button>, the OP's browser is embedding the second button within the first, causing click events to originate in the second and propagate up to the first. The .click handler is then invoked twice for the same click.
I'm not sure if OP wanted the event to only fire one time ever (Barmar's solution) or if he just wants it to fire once per click (my solution). I can delete my answer if the first ends up being true.
Closing the buttons should be correct. The markup in the OP is invalid, so it is unlikely that it behaves as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.