Joe
Joe

Reputation: 1645

Get the ID of the last clicked - jQuery

I have three div's...

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>

When I click on a random div, it moves the order of the div to the top (Let's use ID #2 for example). So the div's could be out of chronological order after this point. Example below...

<div id="2"></div>
<div id="1"></div>
<div id="3"></div>

So if this is the case, is there a way to get the last div ID I clicked?

Upvotes: 1

Views: 5175

Answers (7)

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Do you mean this?

var lastID;

// document.ready
$(function() {
    $("div").on("click", function() {
        lastID = $(this).attr("id");
    });
});

function something() {
    // lastID is the id of the last div clicked.
}

Declaring lastID outside the document.ready function means it's globally accessible, so you can use it in other functions later.

Upvotes: 5

Code Junkie
Code Junkie

Reputation: 1372

I actually often use classes for this like:

HTML:

<div class="orderable">
  <div id="1"></div>
  <div id="2"></div>
  <div id="3"></div>
</div>

jQuery:

$(".orderable").on("click", "div", function() {
  $(".orderable .lastClicked").removeClass("lastClicked");
  $(this).addClass("lastClicked").prependTo(".orderable");
});

So that when things move around, I have the last element identified:

On div click:

<div class="orderable">
  <div id="2" class="lastClicked"></div>
  <div id="1"></div>
  <div id="3"></div>
</div>

Also as others have mentioned, in your example, the last clicked may always be the first in the list in which case you could go:

jQuery:

$(".orderable div:first") // Probable selector for last clicked

Upvotes: 0

adeneo
adeneo

Reputation: 318322

var lastClicked;

$("div").on("click", function() {
    console.log(lastClicked); //last one
    console.log(this.id); //this one
    lastClicked = this.id; //makes this the last one
});

Upvotes: 1

Dan Spiteri
Dan Spiteri

Reputation: 373

Make a var named LastId, make this var outside of the click function. and inside the click funciton update it with its id. so like

$(document).ready(function(){
    var LastId = "";

    $('div').on("click",function() {
        LastId = $(this).attr('id');
    });
});

Hope this helps :D

Upvotes: 0

mas-designs
mas-designs

Reputation: 7546

var lastOne="";   
 $(function({   
        $('div').on("click",function(){
           console.log(lastOne+"div was clicked before");
            lastOne=$(this).attr('id');// id of the clicked div           
        });
    }));

maybe this helps you !

Upvotes: 0

lamplightdev
lamplightdev

Reputation: 2081

The last one you clicked will be at the top, so use the :first selector:

var lastId = $('div:first').attr('id');

Upvotes: 3

trapper
trapper

Reputation: 12003

lastId = $("div#parent div:first").attr('id');

Upvotes: 0

Related Questions