Your elements won't ever touch, because your selector $('div')
which you are animating will animate both divs and move them both by the same amount. They will end up the same distance apart.
Also, you can't use <div2>
as a tag name. Instead, use an id
attribute to assign them a unique name, like this:
<div id="div1"></div>
<div id="div2"></div>
Then instead of animating $('div')
, animate $('#div1')
.
--EDIT--
I misread your question, I thought you were asking how to get them to touch. If you want to detect that they have overlapped, you can use the step
function of the animation to check if the right side of div1 crosses the left side of div2. Try this:
$(document).ready(function(){
// when the buttom is clicked
$('button').click(function(){
// get the left position of div2
var div2Left = $('#div2').position().left
// animate so that the right side of div1 matches div2's left
$('#div1').animate({
'right': '250px',
}, {
// this is called every step of the animation
step: function(currentRightPos) {
// check if collision occurs
if (currentRightPos >= div2Left) {
console.log('The divs collided!');
}
}
});
});
});