javascripthtmlaudiosoundjs

Adding event.preventDefault() Kills SoundJS


I have an existing javascript game I'm trying to add sound to using SoundJS. The problem I'm having is that the line of code that prevents the iphone from dragging the window around when the player moves their finger across the screen is also causing all sounds to not play. If I comment out that single line ("e.preventDefault();"), the sound works perfectly, but the game is unplayable. Has anyone else run into this? Here's the complete function for getting the mouse coordinates:

function mouse_move (finger, e)
  {
  if (!e) var e = event;
  if (finger == true) e.preventDefault();

  main_target_x = e.pageX - canvas_html.offsetLeft;
  main_target_y = e.pageY - canvas_html.offsetTop;
  }

Solution

  • Issue resolved.

    I found a slightly alternate way of preventing the screen dragging, which does not seem to interfere with the sound. My event handlers:

    canvas_html.addEventListener   ("mousedown",   function() {mouse_down (false)}, false);
    canvas_html.addEventListener   ("mousemove",   function() {mouse_move (false)}, false);
    canvas_html.addEventListener   ("touchstart",  function() {mouse_down (true)},  false);
    canvas_html.addEventListener   ("touchmove",   function() {mouse_move (true)},  true);
    canvas_html.addEventListener   ("touchend",    function() {mouse_up (true)},    false);
    document.body.addEventListener ("mouseup",     function() {mouse_up (false)},   false);
    document.body.addEventListener ("touchcancel", function() {mouse_up (true)},    false);
    document.body.addEventListener ('touchmove',   function (event) {event.preventDefault()}, false);
    

    I commented out the "preventDefault" in my mouse_move() function and added a new event handler for 'touchmove' at the end of the list, just to handle the "preventDefault".

    This was just a wild guess, and I'm not entirely sure why it works this way and not the other way. It does, indeed, work, however, and I now have both sound and a stable screen.