Jump to content
Darren

Keyboard Arrow Click Enable the CSS/Javascript Slideshow

Recommended Posts

I have implemented the CSS/Javascript slideshow from https://www.w3schools.com/howto/howto_js_slideshow.asp with a few tweaks on a friend's portfolio site: 

http://bradireland.com/index.html

I've had a request to make the left and right arrows work if the user clicks the left and right arrows on their keyboard, or swipes left and right on a tablet/laptop.

Anyone had any success with either of these? Hoping to not replace the existing code but add to it, if possible.

Thanks!

 

Share this post


Link to post
Share on other sites

For the keys, you can hook into events like keydown or keyup or keypress, check which key they pressed, and take action from there.  For swiping, it sounds like you need to handle the touchstart and touchend events, figure out where each one us, and determine the direction.  There are some examples here:

https://gist.github.com/SleepWalker/da5636b1abcbaff48c4d

Share this post


Link to post
Share on other sites

Thank you. Just learning Javascript now. Is there a way to elegantly add the keypress event into the current code? The left and right arrows are coded by:

 

<button class="w3-button w3-black w3-display-right2" onclick="plusDivs(-1)">&#60;</button>

<button class="w3-button w3-black w3-display-right" onclick="plusDivs(1)">&#62;</button>

 

And the script:

 

<script>
var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  if (n > x.length) {slideIndex = 1}    
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
     x.style.display = "none";  
  }
  x[slideIndex-1].style.display = "block";  
}
</script>

Share this post


Link to post
Share on other sites

You use addEventListener to add an event listener to the page, and key events are usually just added to the body.  If you want to run the same functions as when they click those two buttons, that would probably be the easiest.  You'll only have a single event listener for whichever event you want to look for, and that listener will need to check which key they pressed and then call the appropriate function.

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×