If you want to know when two elements overlap or collide with each other, then this may be of use to you. This option doesn’t require any plugins which I feel is the better option.
Below is a very simple way to detect collision between DOM elements. This can be coupled with a window resize function $( window ).resize(function(){}); to allow for continuous detection.
HTML:
<div id="one">One</div>
<div id="two">Two</div>
<span id="result"></span>
CSS:
div {
width:100%;
height:500px;
background:#EEE;
}
#two {
position:absolute;
left:200px;
top:50px;
background:#000;
}
JavaScript:
console.log(isOverlap("#one","#two"));//true
console.log(isOverlap("#one","#three"));//false
var overlap = isOverlap("#one","#two");
if (overlap) {
// Do something when elements are overlapping
} else {
// Do something when elements are not overlapping
}
jQuery:
$("#result").text(isOverlap("#one","#two")+","+isOverlap("#one","#three")+","+isOverlap("#two","#three"));
function isOverlap(idOne,idTwo){
var objOne=$(idOne),
objTwo=$(idTwo),
offsetOne = objOne.offset(),
offsetTwo = objTwo.offset(),
topOne=offsetOne.top,
topTwo=offsetTwo.top,
leftOne=offsetOne.left,
leftTwo=offsetTwo.left,
widthOne = objOne.width(),
widthTwo = objTwo.width(),
heightOne = objOne.height(),
heightTwo = objTwo.height();
var leftTop = leftTwo > leftOne && leftTwo topOne && topTwo leftOne && leftTwo+widthTwo topOne && topTwo leftOne && leftTwo topOne && topTwo+heightTwo leftOne && leftTwo+widthTwo topOne && topTwo+heightTwo < topOne+heightOne;
return leftTop || rightTop || leftBottom || rightBottom;
}
Popular Posts
- Show / Hide div based on dropdown selected using jQuery
- Autosuggestion Select Box using HTML5 Datalist, PHP and MySQL with Example
- Infinite Scrolling on PHP website using jQuery and Ajax with example
- How to Convert MySQL Data to JSON using PHP
- Custom Authentication Login And Registration Using Laravel 8
- Image Lazy loading Using Slick Slider
- Slick Slider Basic With Example
- Google Login or Sign In with Angular Application
- How to change date format in PHP?
- php in_array check for multiple values
- Adaptive Height In Slick Slider
- Slick Slider Center Mode With Example
- How to Scroll to an Element with Vue 3 and ?
- JavaScript Multiple File Upload Progress Bar Using Ajax With PHP
- Slick Slider Multiple Items With Example
Total Views: 229