Show/hide divs following cursor on half of screen width

I have a Splide slider with prev/next buttons following the cursor, but I can’t figure out how to hide the next button div when hovering on the left side of the full width slider and then hide the prev button div when hovering on the right side of the slider?

This is my code so far:

<script>

$(".splide__arrow--next").html("NEXT");
$(".splide__arrow--prev").html("PREV");

// Hide arrow when cursor is outside the slider
function showArrow() {
   $(".splide__arrow").addClass('show');
}

function hideArrow() {
   $(".splide__arrow").removeClass('show');
}

$(".splide").hover(showArrow, hideArrow);

// Make div follow cursor
$(".splide").bind("mousemove", function(e){
  $(".splide__arrow--next, .splide__arrow--prev").css({
    top: e.pageY - $(".splide__arrow--next, .splide__arrow--prev").height()/2,
    left: e.pageX - $(".splide__arrow--next, .splide__arrow--prev").width()/2
  });
});

</script>

>Solution :

You can use the jQuery .width() and .offset() methods to check the position of the cursor in relation to the slider and hide the appropriate button. Here’s an example of how you can achieve this:

<script>

$(".splide").bind("mousemove", function(e){
  var slider = $(this);
  var next = $(".splide__arrow--next");
  var prev = $(".splide__arrow--prev");
  
  if (e.pageX > slider.offset().left + slider.width()/2) {
      prev.hide();
      next.show();
  } else {
      prev.show();
      next.hide();
  }
  
  next.css({
    top: e.pageY - next.height()/2,
    left: e.pageX - next.width()/2
  });
  
  prev.css({
    top: e.pageY - prev.height()/2,
    left: e.pageX - prev.width()/2
  });
});

</script>

This code binds the mousemove event to the slider and checks the position of the cursor in relation to the slider on every move. If the cursor is on the left half of the slider, it will hide the next button and show the prev button. Conversely, if the cursor is on the right half of the slider, it will hide the prev button and show the next button.

Also, you can make some adjustments to the code, like using .splide__arrow.next, .splide__arrow.prev instead of .splide__arrow--next, .splide__arrow--prev and use .fadeIn(), .fadeOut() to make the transition smoother.

Leave a Reply