Pan photo with keys and on touch device

I have the following pen that allows a visitor to pan a photo using a mouse:

I would like to be able to do so using left and right arrow keys and on a touch device, but I’m stuck.

Any suggestions, please?

1 Like

Hi there Gandalf,

as I don’t have a “Smart Phone” I can’t help with
“touch”, but here is the left and right arrow code…

<html lang="en">

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>Official school photos</title>

The internal CSS should be transferred to an external file
<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
  background-color: #f9f9f9;
  font: normal 1em / 1.5em verdana, helvetica, arial, sans-serif;

h1 {
  font-size: 1.33em;
  color: #444;
  text-align: center;
  text-transform: capitalize;
h2 {
  font-size: 1.12em;
  color: #444;
  text-align: center;
p {
  text-align: center;
#photo {
  background-image: url(;
  background-position: 50% 0;
  height: 35em;
  max-width: 50em;
  margin: 1em auto;
  border: 1px solid #999;
  box-sizing: border-box;
  box-shadow: 0.32em 0.32em 0.32em rgba(0, 0, 0, 0.3);
  transition: background-position 0.3s ease;


<h1>Official school photos</h1>
<p>Use left and right arrow keys to pan left and right</p>
<div id="photo"></div>

(function( d, w ) {
   'use strict';

  var count = 50, image = d.getElementById( 'photo' );

  w.addEventListener( 'keydown', function (e) {

    if ( e.keyCode === 37 && count > 1 ) { count = count - 1; }
    if ( e.keyCode === 39 && count < 100 ) { count = count + 1; } =  count + '% 0';

}( document, window ));




Thanks @coothead.

Hi there Gandalf,

note that I edited the post at 2.00pm GMT,
with a simplification of the script. Make sure
that your not using code prior to that time. :winky:


Hi there @coothead

Thanks and noted. And I’ve simplified it further still :wink:


Are you going to post this modification?


'Tis in the updated codepen.

Do touch devices have left and right keys?

Why don’t you just let touch devices swipe left as they usually would.


1 Like

That sounds like just what I want. Thanks @PaulOB

1 Like

You can remove the touchstart code as I was just using that for testing.

  // detect touch
  if ("ontouchstart" in document.documentElement) {
1 Like

I’ve implemented the changes but I’ll have to wait till tomorrow to wind up my ancient tablet.

Hope it’s not too old as support for anyhover media queries are modern browsers only.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.