Search code examples
javascripthtmlcssright-to-left

Why does direction "rtl" stop the button click event from firing in JavaScript?


I have a demo which is working fine (button click is working fine and it moves to next slide). But when I apply direction property on body it stops working fine. My button click handler is not working. My slide does not change.

function handler() {
  document.querySelector(".p").scroll({
    left: 100,
    behavior: 'smooth'
  })
}

document.getElementById("button").addEventListener("click", handler, false)
.rtl {
  direction: rtl;
}

.p {
  position: relative;
  width: 100px;
  height: 100px;
  overflow: hidden;
  left: 0%;
}

.b {
  width: 100px;
  height: 100px;
  position: absolute
}

.r {
  background-color: red;
  left: 0;
}

.bl {
  background-color: blue;
  left: 100px;
}

.g {
  background-color: green;
  left: 200px;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body class="rtl">

  case : 1
  <div class="p">
    <div class="b r">1</div>
    <div class="b g">1</div>
    <div class="b bl">1</div>
  </div>
  <button id="button">move</button>
  <hr/>

</body>

</html>

when you comment the class rtl then button click wors. why?


Solution

  • When you use right-to-left, all horizontal positioning is reversed. You need to use right instead of left in all the CSS styles. And the scroll amount should be negative to scroll in the opposite direction.

    function handler() {
      document.querySelector(".p").scroll({
        left: -100,
        behavior: 'smooth'
      })
    }
    
    document.getElementById("button").addEventListener("click", handler, false)
    .rtl {
      direction: rtl;
    }
    
    .p {
      position: relative;
      width: 100px;
      height: 100px;
      overflow: hidden;
      left: 0%;
    }
    
    .b {
      width: 100px;
      height: 100px;
      position: absolute
    }
    
    .r {
      background-color: red;
      right: 0;
    }
    
    .bl {
      background-color: blue;
      right: 100px;
    }
    
    .g {
      background-color: green;
      right: 200px;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    
    <body class="rtl">
    
      case : 1
      <div class="p">
        <div class="b r">1</div>
        <div class="b g">1</div>
        <div class="b bl">1</div>
      </div>
      <button id="button">move</button>
      <hr/>
    
    </body>
    
    </html>