3

I am quite new to javascript and jquery so this might be a really simple problem. Please don't mind.

I am appending new link(a) elements in division with id = "whatever" by

$("#whatever").append(jQuery('<a>').attr('href', 'url').text('blah'));

And calling a function

$(function () {
  $('#whatever a').tagcloud();
});

on every link element inside that particular div. But this function is being called only on old elements and not on the ones that I just dynamically added. I tried doing this:

$(document).on("change", '#whatever', function () {
    $("whatever a").tagcloud();  
});

But its still not working.

VikkyB
  • 1,440
  • 4
  • 16
  • 26

6 Answers6

1
var $link = $('<a>').attr('href', 'url').text('blah');
$("#whatever").append($link);
$link.tagcloud();

$(document).on("change" will never fire.

Alex
  • 11,115
  • 12
  • 51
  • 64
1

A response to your edit, try this:

$(document).on("change", '#whatever', function () {
    $("#whatever a").tagcloud();  
});

I think you might have forgotten the # in your selector.

James Y
  • 67
  • 1
  • 7
0

First in your example $("whatever a") should be $("#whatever a") but also when I have this situation I delegate in the same action as the append

$("#whatever").append(jQuery('<a>').attr('href', 'url').text('blah'));
$('#whatever a').off();
$('#whatever a').tagcloud();
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
0

Try this:

$("body").on("tagcloud", "#whatever", function(){
     $("#whatever").append(jQuery('<a>').attr('href', 'url').text('blah')); 
});

Check this similar question out for more info:

Event binding on dynamically created elements?

Also, jQuery has some info on it:

http://api.jquery.com/on/

I wanted to leave this as a comment, but couldn't. Hope it helps.

Community
  • 1
  • 1
James Y
  • 67
  • 1
  • 7
  • Check the edit. Also, if you are going to -1 something, its kind to leave a comment why. I added an example that I hope works and also provided documentation on this subject. – James Y Nov 30 '13 at 20:53
0

It seems it doesn't work as expected as you are missing adding rel attribute to the to-be-appended element(s).

// ...
// The plugin reads the rel attributes
var tagWeights = this.map(function(){
   return $(this).attr("rel");
});

Try this:

$('<a>').attr({'href': 'url', 'rel': 'value'})
        .text('blah')
        .tagcloud()
        .appendTo('#someWhere');

http://jsbin.com/uBAzItuj/3

Ram
  • 143,282
  • 16
  • 168
  • 197
-1

Try this:

$('#whatever').on('change', 'a', function() {
     $(this).tagcloud();
 });
sideroxylon
  • 4,338
  • 1
  • 22
  • 40