How can I get the URL for an API if the URL I want is in the API's JSON?
This is reapplying the click with every call:
function getAPI(apiurl){ $.getJSON(apiurl, function(data) { //Does some stuff then $(".nextPage").on("click", function(){ titleList.length = 0; artistList.length = 0; imgList.length = 0; idList.length = 0; $(".trackList").empty(); getAPI(data.next_href); }) });}
Each time it's called, the number of click handlers goes up by 1 and each will be called.
To stop reapplying it, remove it then apply it. off()
does the removal.
function getAPI(apiurl){ $.getJSON(apiurl, function(data) { //Does some stuff then $(".nextPage").off("click").on("click", function(){ titleList.length = 0; artistList.length = 0; imgList.length = 0; idList.length = 0; $(".trackList").empty(); getAPI(data.next_href); }) });}
To make life easier in the future, separate your onclick
binding from the getAPI
call.
If the button isn't present in the DOM until some event happens, bind to a parent element and they'll be no need for off
/on
:
$("PARENT OF THE .nextPage BUTTON").on("click", ".nextPage", function(){ ...})