Jon
Jon

Reputation: 976

How can you target a previous $(this)?

I have a function that is fired when a user clicks on a link. When they click on another link, I want to alter the first link that they clicked on. How would I go about doing this? This is what I have so far:

$('a').click(function(){
  //some code ...
  if ( $(this).attr('id') != last.attr('id') ) {
    $('a').click(function()
      /*the original $this*/.parent().parent().quickFlipper({refresh: 0});
      /*the original last*/.parent().parent().quickFlipper({refresh: 0});
    });
    var that = this;
    var that2 = last;
    setTimeout(function(){
      $(that).parent().parent().quickFlipper({refresh :0});
      $(that2).parent().parent().quickFlipper({refresh :0});
    }, 1500);
  //some more code ...
});

Thanks in advance and please ask any questions if you are unsure of what I am trying to accomplish.

Upvotes: 2

Views: 670

Answers (4)

John Strickler
John Strickler

Reputation: 25421

This is a good time to use a closure.

$('a').click((function () {

   //private
   var lastClicked;

   return function () {
      //your code

      if(lastClicked) {
         //do something to the last clicked element
      }

      lastClicked = this;
   };
})());

Fiddle: http://jsfiddle.net/iambriansreed/Mus6N/

Upvotes: 3

Adam Merrifield
Adam Merrifield

Reputation: 10407

Use a global var for last.

something like

$(function(){
    var lastClick;
    $('a').click(function(){
        //do stuff to last click here
        lastClick = $(this); //make this at the bottom
    });
});

Upvotes: 0

Bob Davies
Bob Davies

Reputation: 2282

var lastClicked = null;

$('a').click(function(){
  //some code ...
  if (lastClicked && $(this).attr('id') != lastClicked.attr('id') ) {
       $(this).parent().parent().quickFlipper({refresh: 0});
      lastClicked.parent().parent().quickFlipper({refresh: 0});

    lastClicked = $(this);
  }
});

like that?

Upvotes: 0

Sully
Sully

Reputation: 14943

var previousElement;

$('a').click(function(){
  //some code ...
  previouseElement = ($this);
  if ( $(this).attr('id') != last.attr('id') ) {
    $('a').click(function()
      $(this).parent().parent().quickFlipper({refresh: 0});
      previousElement.parent().parent().quickFlipper({refresh: 0});
    });
    var that = this;
    var that2 = last;
    setTimeout(function(){
      $(that).parent().parent().quickFlipper({refresh :0});
      $(that2).parent().parent().quickFlipper({refresh :0});
    }, 1500);
  //some more code ...
});

Upvotes: 0

Related Questions