Home > Software design >  How to make an invisible clickable area that would toggle scrolling (JavaScript)?
How to make an invisible clickable area that would toggle scrolling (JavaScript)?

Time:11-20

I'm making a small website built entirely with flexbox columns and rows. One of the rows is horizontally scrollable — howewer, I want it to be scrolled not only with scrolling, but also by clicking either on left or right half of the visible part of the row. Plus, hovering on the left side should change cursor to cursor: w-resize and on the left side — to cursor: e-resize.

see screenshot see a sketch of what i'm trying to achieve

    <div >
      <div >
       <div id="project-image"><img id="image-standart-height" style="max-height: 400px" src="/Users/andrei/Desktop/All Work/portfolio and cv/my website/images/bahorvesna.png" alt=""></div>
       <div id="project-image"><img id="image-standart-height" style="max-height: 400px" src="/Users/andrei/Desktop/All Work/portfolio and cv/my website/images/bahorvesna.png" alt=""></div>
       <div id="project-image"><img id="image-standart-height" style="max-height: 400px" src="/Users/andrei/Desktop/All Work/portfolio and cv/my website/images/bahorvesna.png" alt=""></div>
       <div id="project-image"><img id="image-standart-height" style="max-height: 400px" src="/Users/andrei/Desktop/All Work/portfolio and cv/my website/images/bahorvesna.png" alt=""></div>

      </div>
      <div >
Bahor/Vesna
      </div>
      </div>

#project-image {
  flex: 0 0 auto;
  max-height: 400px;
}

#image-standart-height {
  max-height: 400px;
}

.project-text {
  display: flex;
  gap: 20px;
  align-items: baseline;
}

I was thinking of creating an invisible layer on a different z-axis level, but I assume it would be difficult not to ruin the flexbox.

Is it possible to make a function in JS to detect when a mouse is entering a certain area of the visible part of the div, change cursor and make the area clickable?

CodePudding user response:

You can also do it without adding any extra div's, by checking the position of the mouse pointer relative to the container. Try it out by clicking the left and right half of the box in the example.

const container = document.getElementById('container');

container.addEventListener('click', (e) => {
  const clientRect = e.currentTarget.getBoundingClientRect();
  if ((e.pageX - clientRect.left) < clientRect.width / 2)
    console.log('Clicked left half');
  else
    console.log('Clicked right half');
});

container.addEventListener('mousemove', (e) => {
  const clientRect = e.currentTarget.getBoundingClientRect();
  if ((e.pageX - clientRect.left) < clientRect.width / 2)
    container.style.cursor = 'w-resize';
  else
    container.style.cursor = 'e-resize';
})
#container {
  width: 300px;
  height: 100px;
  border: 1px solid #000;
  margin: 50px auto;
}
<div id="container"></div>

  • Related