o037
o037

Reputation: 137

Javascript onmouseup event not firing as expected

I'm working on a tilemap constructor app that uses paint-like functionality to select a tile (src from an image element) and paint it using mouseup and mousedown event handlers.

For whatever reason the mouseup event is not firing as expected. I've read that mouseup will not fire if mousemove is active, and I am running the preventDefault function on mousemove and mousedown. This seems to work only when I don't have a tile selected.

Here is my event handler function:

function setTilemapMouseEvents() {
    var tilemap = document.getElementById('tilemap');

    tilemap.addEventListener('mousedown', function(e) {
        window.mouseDown = true;
        e.preventDefault();
    });

    tilemap.addEventListener('mousemove', function(e) {
        e.preventDefault();
    });

    window.addEventListener('mouseup', function() {
        window.mouseDown = false;
    });
}

My tile selecting functions:

function TilesetTile(options) {
    this.image = options.image;
    this.symbol = options.symbol;
}

function selectTile(element) {
    var selectedTile = document.getElementsByClassName('selected')[0];
    if (selectedTile !== undefined) {
        selectedTile.classList = 'tileset-tile';
    }
    element.classList += ' selected';
    window.selectedTile = new TilesetTile({image: element.src});
}

and my painting function (called by an onmouseover event on the tile elements):

function paintTile(element) {
    if (window.mouseDown && window.selectedTile) {
        element.innerHTML = '<img src="' + window.selectedTile.image + '" class="tilemap-tile"/>';
    }
}

I think this may be a Chrome specific issue. I tried it on Safari real quick and it seemed to work fine. Any insight on what is causing this would be helpful.

Upvotes: 2

Views: 578

Answers (1)

o037
o037

Reputation: 137

Okay, so I still have no idea what was causing this behavior, but I was able to isolate it to the third line of the paintTile function:

element.innerHTML = '<img src="' + window.selectedTile.image + '" class="tilemap-tile"/>';

Something in this line was interfering with my mouseup event being fired. Still have no idea why. I was able to remedy the behavior by wrapping it in a requestAnimationFrame call like so:

window.requestAnimationFrame(function() {
            element.innerHTML = '<img src="' + window.selectedTile.image + '" class="tilemap-tile"/>';
        });

So my issue is solved, but I would still be interested in knowing what could cause this kind of behavior. Please comment if you have any ideas. Thanks,

Upvotes: 2

Related Questions