user9645391
user9645391

Reputation:

How to make If Statements work simultaneously?

Consider a div which is square and I have detected the centers vertically and horizontally, In OnMouseMove event I want to perform rotateX and rotateY on the element if from centers get close to top,left, right, bottom. I have written the code below and works nicley:

var CSSProperties = 
`
  transition-duration: 250ms;
  transition-timing-function: linear;
  transition-delay: 0;
  transition-property: unset;
  transform: 
`;

if (xPosition > xDivided) {
  DOMElement.style.cssText = CSSProperties + `rotateY(${xFormula}deg);`;
}

if (xPosition < xDivided) {
  DOMElement.style.cssText = CSSProperties + `rotateY(${xFormula}deg);`;
}

if (yPosition < yDivided) {
  DOMElement.style.cssText = CSSProperties + `rotateX(${yFormula}deg);`;
}

if (yPosition > yDivided) {
  DOMElement.style.cssText = CSSProperties + `rotateX(${yFormula}deg);`;
}

I have 2 problem:

  1. With this sort of If Statement writing, it works only vertically not horizontal as when I remove vertically codes, It works in horizontal.

  2. When mouse get close to corners It just works in horizontal or vertical not both of them.

I think my problem should be here but I can't resolve it, Any help will be appreciated.

Upvotes: 0

Views: 70

Answers (1)

nadavvadan
nadavvadan

Reputation: 4190

Basically, your code overrides DOMElement.style.cssText inside every if statement.
So let's say the first and third if statements are true; In this case, transform will be set to CSSProperties + `rotateY(${xFormula}deg);`, only to be immediately set to `rotateX(${yFormula}deg);`, overriding the previous one. Because of the order of your if statements, in which the vertical calculation comes after the horizontal one, the vertical transform property (rotateX) will override the horizontal one (rotateY).

Instead, you can append to the end of CSSProperties, such that both transforms are added. Then all you have to do is set DOMElement.style.cssText to CSSProperties, which contains both of your transforms.

var CSSProperties = 
`
  transition-duration: 250ms;
  transition-timing-function: linear;
  transition-delay: 0;
  transition-property: unset;
  transform: 
`;

if (xPosition > xDivided) {
  CSSProperties += `rotateY(${xFormula}deg)`;
}

if (xPosition < xDivided) {
  CSSProperties += `rotateY(${xFormula}deg)`;
}

if (yPosition < yDivided) {
  CSSProperties += `rotateX(${yFormula}deg)`;
}

if (yPosition > yDivided) {
  CSSProperties += `rotateX(${yFormula}deg)`;
}

DOMElement.style.cssText = CSSProperties + ';';

Upvotes: 3

Related Questions