herrmarek
herrmarek

Reputation: 805

Scope inside jQuery load() function

I am having a problem with the scope. Sorry for this noobish question.

I am trying to append images to a parent div with jQuery, but don't know how to pass the variable "theParent" to the load function.

// inside a this.each loop

    var theParent = $(this).parent('div.parent'); 

    var img = $("<img />")
                .attr('src', '/path/img.jpg')
                .error(function(){ console.log('error'); })
                .load(function(){
                    img.addClass('myClass'); // <-- not working plz help
                    theParent.append(img); // <-- not working plz help
                    });

Upvotes: 1

Views: 785

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206218

LIVE DEMO

$(this).addClass('myClass'); would work but use:

var img = $("<img />", {
          "src"   : '/images/favicon.png',
          "class" : 'myClass'
      })
      .error(function(){ console.log('error'); })
      .load(function(){
                img.appendTo( theParent ); 
      });

Upvotes: 3

Sandeep
Sandeep

Reputation: 43

Have you tried the following:

$('#theDiv').prepend('<img id="theImg" class="myClass" src="theImg.png" />')

Upvotes: 0

Zach
Zach

Reputation: 3207

Per http://api.jquery.com/load-event/ "this" is the object the load event is attached to.

Upvotes: 0

fernandosavio
fernandosavio

Reputation: 10387

Try this:

var theParent = $(this).parent('div.parent'); 

    var img = $("<img />", {
      src: '/path/img.jpg',
      "class": 'myClass' 
    }).appendTo(theParent);

Upvotes: 0

Related Questions