VikkyB
VikkyB

Reputation: 1450

Call function on dynamically added elements

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.

Upvotes: 3

Views: 2205

Answers (6)

Ram
Ram

Reputation: 144669

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

Upvotes: 0

James Y
James Y

Reputation: 67

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.

Upvotes: 1

James Y
James Y

Reputation: 67

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.

Upvotes: 0

chiliNUT
chiliNUT

Reputation: 19573

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();

Upvotes: 0

sideroxylon
sideroxylon

Reputation: 4416

Try this:

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

Upvotes: -1

Alex
Alex

Reputation: 11245

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

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

Upvotes: 1

Related Questions