You only bind the click()
if there's not already an image, but within the click()
(which can be invoked several times) you're not performing this check. Therefore,
$(document).ready(function(){
$("#map_container").click(function (e) {
if ($(this).find('#point').length == 0 ) {
var relativeXPosition = (e.pageX - this.offsetLeft);
var relativeYPosition = (e.pageY - this.offsetTop);
//alert('left: '+relativeXPosition+', top: '+relativeYPosition);
$("#map_container").append('<img id="point" src="<?=url::base();?>images/city.png" alt="" />');
$("#point").css({ top: (relativeYPosition) + 'px', left: relativeXPosition + 'px', position: 'absolute' })
}
});
});
To elaborate: In your code the click()
handler is bound once (depending on the condition - which I suspect to always return true) but can be invoked several times always producing the same output. In the above, however, the click()
handler performs the check on every invocation, thus only producing output when the condition is false (i.e., there is no #point
yet).
EDIT: unbind()
/ one()
@tsimbalar has a pretty neat solution using unbind()
. That's clever if your click()
does not contain an else
part (to be executed if #point
does exist). The same can be achieved by means of one()
: $(...).one('click', function() { ... });
$(document).ready(function(){
$("#map_container").one('click', function (e) {
var relativeXPosition = (e.pageX - this.offsetLeft);
var relativeYPosition = (e.pageY - this.offsetTop);
//alert('left: '+relativeXPosition+', top: '+relativeYPosition);
$("#map_container").append('<img id="point" src="<?=url::base();?>images/city.png" alt="" />');
$("#point").css({ top: (relativeYPosition) + 'px', left: relativeXPosition + 'px', position: 'absolute' })
});
});