0

My javascript code is not running, but the html drawing the canvas is..... Im trying to add an event listener on a canvas html element. Each time i click the element its supposed to give me an alert. Ive tried this on firefox and google chrome.

<script language = "javascript" type = "text/javascript">

alert("yo");
canvas.addEventListener('click', function() {}, false);



var elem = document.getElementById("checkersq"),
elemLeft = elem.offsetLeft,
elemTop = elem.offsetTop,
context = elem.getContext('2d'),
elements = [];

elem.addEventListener('click', function(event){

    var x = event.pageX - elemLeft, 
        y = event.pageY - elemTop;

    elements.forEach(function(element){

        if (y > element.top && y < element.top + element.height
            && x > element.left && x < element.left + element.width){

                    alert('clicked an element');

            }

        }   
    });
}, false);

elements.push({
    colour: '#05EFFF',
    width: 150,
    height: 200,
    top: 20,
    left: 15
});

elements.forEach(function(element) {

    context.fillStyle = element.colour;
    context.fillRect(element.left, element.top, element.width, element.height);
});

4
  • Not an answer, but lose those spaces: language="javascript" type="text/javascript" Commented Mar 21, 2013 at 4:25
  • What browser? Any errors in the JavaScript console? Commented Mar 21, 2013 at 4:26
  • Also keep in mind that forEach is not standard yet. Commented Mar 21, 2013 at 4:27
  • 1
    Also canvas is never defined. Commented Mar 21, 2013 at 4:30

1 Answer 1

2

convert

}   
    });
}, false);

to

    });
}, false);
Sign up to request clarification or add additional context in comments.

1 Comment

i figured it out. I was suposed to do window.onload function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.