The code below takes a div and moves it on click. The return button the moves the div back to where it was before. The second alert gets triggered multiples times on occasion. Can someone explain why?
<html>
<head>
<script src="js/jquery.js"></script>
<style>
.profile {
width: 250px;
height: 250px;
margin-top: 250px;
margin-left: 250px;
border: solid black 1px;
}
</style>
</head>
<body>
<script>
$(document).ready(function(){
$('.profile').click(function(){
// store current position
var activeProfile = $(this);
var profilePosition = activeProfile.offset();
var initialLeft = profilePosition.left;
var initialTop = profilePosition.top;
alert(initialLeft);
$(this).css({'position' : 'absolute', 'top' : 0, 'left' : 0, 'margin': 0});
// return to original start position
$('#close').click(function(e) {
alert('sometimes i get triggered multiple times!');
activeProfile.css({'left' : initialLeft, 'top' : initialTop});
e.stopPropagation();
});
});
})
</script>
<div class="profile">
<button id="close">Return</button>
</div>
</body>
</html>
Looks like the culprit is that every time you click the .profile class it associates a event to #close .. So if you click twice it binds two times.. So you need to unbind and associate again to see the alert only once..
This is the FIDDLE for old code
This is the UPDATE FIDDLE with unbind event associated with it..