Pedro
Pedro

Reputation: 575

Re-targeting jQuery "this"

I have this code:

$('.mainDiv').on('click', function(){
  $(this).animate({'width':'70%', 'height':'70%'}, 300, 'swing');
  $('p', this).stop().animate({'font-size':'70%', 'color':'#000000', 'opacity':'1'}, 300, 'swing',
    function(){
      $(?????).animate({'width':'110%', 'height':'110%', 'opacity':'0'}, 300, 'swing');
    }
  );
});

Question: (?????) how do I re-target ".mainDiv" after targeting it's child "p" ?

Upvotes: 0

Views: 61

Answers (3)

Kamil T
Kamil T

Reputation: 2216

I wold rather suggest using:

$('.mainDiv').on('click', function(){
  var that = this;
  $(this).animate({'width':'70%', 'height':'70%'}, 300, 'swing');
  $('p', this).stop().animate({'font-size':'70%', 'color':'#000000', 'opacity':'1'}, 300, 'swing',
  function(){
      $(that).animate({'width':'110%', 'height':'110%', 'opacity':'0'}, 300, 'swing');
  });
});

The main idea is to 'attach' the variable to some other, I personaly like it being called 'that', but there are few possible approaches.

Upvotes: 1

Felice Pollano
Felice Pollano

Reputation: 33252

You can use:

var $this=$(this);

and then use $this when you need to refer the original element.

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382170

You can do this :

$('.mainDiv').on('click', function(){
  var $maindiv = $(this); // <= save the external "this"
  $maindiv.animate({'width':'70%', 'height':'70%'}, 300, 'swing');
  $('p', this).stop().animate({'font-size':'70%', 'color':'#000000', 'opacity':'1'}, 300, 'swing',
    function(){
      $maindiv.animate({'width':'110%', 'height':'110%', 'opacity':'0'}, 300, 'swing');
    }
  );
});

Upvotes: 4

Related Questions