Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading