JQuery - Can't select dynamically created URL tag by class
-
24-01-2021 - |
Question
So I am creating a TagCloud for my site and am having issues being able to use JQuery to alert me of the selected link. The site created the links just fine, gives them the class of 'tagLink', but when I try to alert the number of elements with that class, it gives me 0. Any ideas?? Here is my code:
$(function() {
//get tag feed
$.getJSON("tagcloud/tagcloud.php?callback=?", function(data) {
//create list for tag links
$("<ul>").attr("id", "tagList").appendTo("#tagCloud");
//create tags
$.each(data.tags, function(i, val) {
//create item
var li = $("<li>");
//create link
$("<a>").addClass('tagLink').text(val.tag).attr({title:"See all pages tagged with " + val.tag, href:"tags/" + val.tag + ".php", id: val.tag}).appendTo(li);
//set tag size
li.children().css("fontSize", (val.freq / 10 < 1) ? val.freq / 10 + 1 + "em": (val.freq / 10 > 2) ? "2em" : val.freq / 10 + "em");
//add to list
li.appendTo("#tagList");
});
});
//Increase database if link is clicked
alert($('.tagLink').size());//Test how many exist
$('.tagLink').click(function(){
var id = $(this).attr('id');
$.ajax({
url: "tagcloud/tagcloud.php",
type: "POST",
data: {clicked : id}
});
});
});
Solution
getJSON is asynchronous so your selector gets run before the tag links get added. Move the taglink click handler assignment inside your AJAX callback.
OTHER TIPS
You can use $.get() or $.ajax() instead.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow