Question

I'm pretty new to programming and I need some help getting this code to work for an experiment I'm running (in grad school). I want the user to be able to adjust the opacity of an image by pressing the left and right arrow keys. I'm also doing this in Qualtrics, if that matters. The following javascript code is not working for me... Your help is much appreciated!

var op =0.1;
var op1 = 10;
var step = 10;
var min = 0.1, max = 1;
var min1 = 10, max1 = 100;

var image = document.getElementById("image");
image.style.opacity = op;
image.style.filter = alpha(opacity=op1);

Event.observe(document, 'keydown', function(e) {
  if(e.keyCode == 37) {
    op-=step;
    op1-=step;
    op = Math.max(min, op);
    op1 = Math.max(min, op1);
  } else if(e.keyCode == 39) {
    op+=step;
    op1+=step;
    image.style.opacity = Math.min(max, op);
    op1 = Math.min(max, op1);
  }
});
Was it helpful?

Solution

I've modified the code slightly to get it to work without having the rest. Hopefully you'll be able to get everything to work correctly from this:

var op =0.1;
var op1 = 10;
var step = .1; //changed to .1 from 10
var min = 0.1, max = 1;
var min1 = 10, max1 = 100;

var image = document.getElementById("image");
image.style.opacity = op;
//image.style.filter = alpha(opacity=op1); //removed (implement browser check if IE) 

$(document).on('keydown', function(e) {
  if(e.keyCode === 37) { //made === (preference)
    op-=step;
    op1-=step;
    op = Math.max(min, op);
    op1 = Math.max(min, op1);
    image.style.opacity = Math.min(max, op); //added 
  } else if(e.keyCode === 39) {//made === (preference)
    op+=step;
    op1+=step;
    image.style.opacity = Math.min(max, op);
    op1 = Math.min(max, op1);
  }
});

Example

Note: You'll need to click into the results box (bottom right) in the example above before hitting the left/right arrow keys.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top