I am writing a script using jQuery to add multiple control boxes(divs) to a web page. These divs contain controls (anchors) like close, prev, next, search etc. A code sample:
$div_overlay =
$('<div></div>')
.addClass('overlay')
.append($('<div></div>')
.addClass('text_controls')
//The onClick method below works perfect but not .click() of jQuery(due to the way 'index' is used)
.append($('<a onClick="overlay_hide('+index+'); return false;"></a>')
.addClass('close')
.attr('href','#')
/*.click(function(){
//The 'index' gets incremented as divs are created and hence a wrong value(the last one) is passed irrespective of the div clicked
overlay_hide(index)
})*/
)
'index' is a global var to keep track of the 'overlay' divs created. It is incremented as the divs are created and each div is pushed in an array as it is created. So, 'index' is basically the array index of a div.
To keep it simple, I only added the 'close' anchor. The $div_overlay
is in a function which is called every time an image is clicked.
My problem is to handle the click events for the anchors like 'close'. I would like to identify the div for which the anchor is clicked using an 'index' which is a global var.
I would like to be able to pass a reference to the div on which the close action is performed. If I use the jQuery click method which is commented in above code to close the div, it passes the last index value as the parameter to overlay_hide()
(since index is incremented as the divs are created). If I use the onClick method as above, it works fine by passing the correct index value.
So, how do I identify these divs using indexes and be able to uniquely access them based on which div control is clicked? (Probably objects need to be used but I am not sure.)
One way would be to get the parent of the clicked anchor but I do not want to do it that way and would like to use an index.
You could add meta data to the anchor with a data attribute.
$('<a data-index="' + index + '"></a>').click(function(){
var data = $(this).data();
overlay_hide(data.index); // note index will be a string
return false;
});
Another way you could do it is with a closure on the click function:
$('<a />').click(function(i){
return function(e){
// use i here this is the callback.
overlay_hide(i);
return false;
};
}(index));
I would also like to point out that you have an id .attr('id','overlay')
being added - and id's must be unique across the DOM.