How can i stop the on-click event from duplicating the results from twitch api?

Hi guys how do i stop my result from duplicating when i use the on-click event. I tried creating if statements saying if what is in the div is equal to the call from the api then it should delete whats in the div and replace with the api data but that does seem to work the way im doing it. Could someone point me on the right direction with this. codepen:

  $(document).ready(function() {
    // solution with call back function
    var streamers = ["streamerhouse","ESL_SC2", "freecodecamp", "Test_channel"];
    for (i=0; i < streamers.length; i++){
    $.getJSON(''+streamers[i]+'', callData);

    function callData(data)
        var textTile
         $(document).on('click', '#offlineNow', function(){
           if(data["stream"] === null){
                   textTile +=  data["_links"]["channel"]
          $(document).on('click', '#onlineNow', function(){
           if (data["stream"] !== null ){

“append” adds it to the end but keeps the original. “html” will overwrite it, So,


should work.

Furthemore, for your JQuery click selector, I’m more used to seeing:


Your way works too I guess, but it’s not what I see most people using.

1 Like

Thanks a lot it doesn’t duplicate now i only get the last result generated from the for loop now though.

OK, first of all, you really need to keep your code cleaner. Indent properly, please. It will make it easier for people to help you. And I recomend putting incline comments after closing curly braces that are far from their open braces - it makes it a lot easier to see what is happening. Incline comments like “// doc ready” or “// for i loop” or “// getJSON();”

Secondly, it seems odd to me that you have your click handler inside the for loop. Does that mean that multiple click handlers are being generated? I don’t know enough about JS to know.

I would use the for loop to make an array of data and then have click handlers outside of that to make my write the list to the html. You can start with a “$(’#streamerOnline’).empty()” to clear it out and then loop through your data and use your “$(’#streamerOnline’).append(…” to fill it. Alternatively, you can use a string varliable to keep “+=” the data and then write all of that with a “$(’#streamerOnline’).html(…” Either of those would work. I’d have to do a lot of work to get your solution to work. There are other approaches, but those seem the closest to how you’re thinking at the moment.