Pregunta

So I am making a little game where you have to press Ctrl to stop a div from jumping randomly. However I can't get it working... The jumpRandom function works fine, until i put the randomJump(){return false;}; inside the if (event.ctrlKey) {}. What should I do to get it working?

js:

    $(document).ready(function() {

function randomFromTo(from, to){
            return Math.floor(Math.random() * (to - from + 1) + from);
}
$( "#goal" ).bind('mouseenter keypress', function(event) {
    if (event.ctrlKey) {
            randomJump(){return false;};
        }
});
$('#goal').mouseenter(randomJump);

function randomJump(){
            /* get Window position and size
             * -- access method : cPos.top and cPos.left*/
            var cPos = $('#pageWrap').offset();
            var cHeight = $(window).height() - $('header').height() - $('footer').height();
            var cWidth = $(window).width(); 

            // get box padding (assume all padding have same value)
            var pad = parseInt($('#goal').css('padding-top').replace('px', ''));

            // get movable box size
            var bHeight = $('#goal').height();
            var bWidth = $('#goal').width();

            // set maximum position
            maxY = cPos.top + cHeight - bHeight - pad;
            maxX = cPos.left + cWidth - bWidth - pad;

            // set minimum position
            minY = cPos.top + pad;
            minX = cPos.left + pad;

            // set new position         
            newY = randomFromTo(minY, maxY);
            newX = randomFromTo(minX, maxX);


            $('#goal').fadeOut(50, function(){

                $('#goal').fadeIn(700);
            });
            $('#goal').animate({
                    left: newX,
                    top: newY,
                    duration: 500
                });
        }
});
¿Fue útil?

Solución

Try this:

$("#goal").bind('mouseenter keypress', function (e) {
    randomJump(e);
});

function randomJump(e) {
    if (!e.ctrlKey) {
        //do normal stuff
    } else {
        //depending on how permanent you need this to be...
        //$("#goal").unbind('mouseenter keypress');
    }
    return !e.ctrlKey;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top