Home > Enterprise >  I need help to write specific code using javascript
I need help to write specific code using javascript

Time:01-08

I want to write code something like this:

if ( [*distance between two objects*] = [*for example: 20px*] ) { 
[*run someFunction()*] 
}

I have written many different codes and logics , but it's little different for me...

maybe I have to use the Pythagorean theorem, something like this?

var a = x1 - x2;
var b = y1 - y2;
var c = Math.sqrt( a*a   b*b );
// c is the distance

But how can I practically use it to get something like this:

if ( [*distance between two objects*] = [*for example: 20px*] ) { 
[*run someFunction()*] 
}

Please help me if you can...

CodePudding user response:

You can reorganize your code in two functions to make it more readable. Then use the function in the conditional.


function distance(x1, x2){
    var a = x1 - x2;
    var b = y1 - y2;
    var c = Math.sqrt( a*a   b*b );
    return c;
}


if(distance (x1, x2) > 20){
    someFunction()
}

If you want to calculate the distance between two objects you can use jQuery s offset () function to get the upper left corner and width () and height () to get the lower right corner

read more here https://api.jquery.com/offset/

or you can read here: about how to do it in vanilla js Pure JavaScript function similar to jQuery.offset()?

CodePudding user response:

To get the distance you want to do something like this.

Just bare in mind because I;m using display inline block it add's a little extra margin between elements hence the extra bit of px.

window.onload = function() {
  var eleY = document.getElementById('y'),
    eleX = document.getElementById('x'),
    y = eleY.getBoundingClientRect().left,
    x = eleX.getBoundingClientRect().right,
    distance = y - x;

  eleY.innerHTML = 'y = '   y;
  eleX.innerHTML = 'x = '   x;
  document.getElementById('distance').innerHTML = 'distance = '   distance;
  
  if(distance == 138){
    alert('JUMP');
  }
  
}
div {
  padding:35px 0;
  width: 80px;
  display: inline-block;
  text-align:center;
  vertical-align:middle;
}


#x {
  background: red;
}

#distance {
  width:100px;
  padding:10px 5px;
  color:#fff;
  background:green;
  margin:0 10px;
  
}

#y {
  background: yellow;
}
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script type="text/javascript">
  </script>
</head>

<body>
  <div id="x"></div>
  <div id="distance"></div>
  <div id="y"></div>
 </body>
</html>

  •  Tags:  
  • Related