Reputation: 4264
I have the below code, which is also contained in this fiddle.
<div id="box"><div>click in the box</div></div>
<p>Click a name</p>
<ul>
<li id="id-1">tom</li>
<li id="id-2">jerry</li>
</ul>
<div id="result"></div>
<script>
var id;
var person;
jQuery(document).on("click", "li", function (event) {
id = jQuery(this).attr('id') || '';
person = jQuery(this).text();
$("#box").show();
});
$(function () {
$("#box").click(function (e) {
var d = new Date();
$( "#result" ).append( "<div class='item'>" + person + " last clicked the box at " + d + "</div>");
});
});
</script>
Currently you click on a persons name, then when you click on the box it appends the persons name and the time you clicked on the box.
Instead of having this happen repeatedly I want to append the person if they haven't been clicked before and if they have I want to update there latest item with the last time they clicked the box.
I am really stuck with how I would go about doing this, something like if blank append else update? What is the best way to handle something like this?
Upvotes: 2
Views: 937
Reputation: 59
var cache = {},person,id;
jQuery(document).on("click", "li", function (event) {
id = jQuery(this).attr('id') || '';
$(this).data('appended' , true);
person = jQuery(this).text();
cache[person] = true;
$("#box").show();
});
$(function () {
$("#box").click(function (e) {
var d = new Date();
if( cache[person] ){
//update
}else{
$( "#result" ).append( "<div class='item'>" + person + " last clicked the box at " + d + "</div>");
}
});
});
I wish this code above can help you
Upvotes: 2
Reputation: 337560
You could store the last click date as a data
parameter on the item itself. Then you can easily tell if it has or has not been clicked. Try this:
$(document).on("click", "li", function (event) {
$(this).data('clickdate', new Date());
$("#box").show();
});
$("#box").click(function (e) {
var $box = $(this).empty();
$('li').each(function(i, el) {
var clickDate = $li.data('clickdate');
var $item = $('<p />', {
text: $(el).text() + ' : ' + (clickDate || 'Not clicked')
});
$box.append($item);
});
});
As you can see in the fiddle, this shows all li
elements, even if they have not been clicked. If required, you can remove the unclicked ones by appending the append line to:
clickDate && $box.append($div);
Upvotes: 2
Reputation: 388316
Try
$(function () {
$("#box").click(function (e) {
var d = new Date();
var $div = $('#result .item[data-id="' + id + '"]');
if ($div.length == 0) {
$div = $('<div/>', {
"class": 'item',
"data-id": id
}).appendTo('#result');
}
$div.html(person + ' last clicked the box at ' + d);
});
});
Demo: Fiddle
I might have done it slightly different using a class attribute to mark the clicked item: http://jsfiddle.net/arunpjohny/CDCLF/2/
Upvotes: 1