function handler() { var left = myDIV.getBoundingClientRect(); var top = myDIV.getBoundingClientRect(); if (left = 100){ left.style.left = (parseInt(left.style.left||0)+100)+"px"; } if(top = 100){ top.style.top = (parseInt(top.style.left||0)+100)+"px"; } if (left = 200) left.style.left = (parseInt(left.style.left||0)-100)+"px"; } if(top = 200){ top.style.top = (parseInt(top.style.left||0)-100)+"px"; } 

tell me the direction for the function to work

  • Agree missing after adding gives error Cannot read property 'left' of undefined - Andrew
  • It gives an error, because you are trying to take the left.style.left property, in this case left.style is undefined and it does not have the left property. This property is only for the DOM element (myDIV in your cases) - PavelGorobtsov

1 answer 1

myDIV.getBoundingClientRect(); returns an object of the form {left: 100, right: 100, ...} , i.e. in the variable left and right you put the object. In this case, further in the code, you are reassigning, rather than checking.

Perhaps something like this was originally conceived (it is not clear from the task):

 function handler() { var bounds = myDIV.getBoundingClientRect(); if (bounds.left === 100){ myDIV.style.left = (parseInt(myDIV.style.left||0)+100)+"px"; } if(bounds.top === 100){ myDIV.style.top = (parseInt(myDIV.style.top||0)+100)+"px"; } if (bounds.left === 200){ myDIV.style.left = (parseInt(myDIV.style.left||0)-100)+"px"; } if(bounds.top === 200){ myDIV.style.top = (parseInt(myDIV.style.top||0)-100)+"px"; } } 
  • <div id = "myDIV" onclick = "handler ()"> <h1> myDIV </ h1> </ div> there is a div to it before moving after the click - Andrew
  • Well then yours would almost certainly not have earned. Perhaps this example solves your problem jsfiddle.net/5z35ywad - PavelGorobtsov
  • necessarily what style was in a diva? Is it possible to take it out of the diva? - Andrew
  • Not necessarily, you can use the offsetTop and offsetLeft properties, example jsfiddle.net/5z35ywad/1 - PavelGorobtsov
  • Thanks for the help - Andrew