Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Detect click in certain pixel area, then execute function

I currently have a div, let's call it #videodiv that includes an HTML5 video player (SublimeVideo, but that may be irrelevant information). On page load, #videodiv is only 100px. When a user clicks anywhere within #videodiv, I'd like for jQuery to expand the div to 250px.

You may be saying -- that's as simple as a jQuery function comes, just use click then animate! And you'd be right, except...

Here's the problem: The HTML5 video player that is contained within #videodiv and that fills the entire div captures all clicks that occur. This is done to trigger the play/pause function for the player, but subsequently disallows any programmer to set a jQuery click function for the containing div.

Luckily in this situation, #videodivis a 100% full body-width div and has an exact height of 100px. So, bearing in mind the problem above, the alternative would be to figure out if we can capture any clicks within the HTML document (rather than the div) that occur in the top 100 pixels of the page, then trigger the function.

In other words, how can we use jQuery to detect mouse clicks anywhere within the first 100 pixels of a page, then animate the div videodiv to 250px?

Alternative/better solutions are absolutely more than welcome, but jQuery is the preferred method.

like image 225
Andy Dwyer Avatar asked May 17 '26 01:05

Andy Dwyer


1 Answers

Something like this should work - change the width and height values to match your needs. pageX is lateral and pageY is vertical so I just mapped a 100x100 space in the top left corner. Change that to fit your needs as well:

// Bind the click event to the body - any static parent container will do
$('body').on('click', function(e) {

    // Fire the callback if the click was in the top 100px by 100px
    if (e.pageX <= 100 && e.pageY <= 100) {

        // Prevent crazy animations and redundant handling
        $(this).off('click'); 

        // Scale the video to the appropriate size
        $('#videodiv').animate({
            width  : '250px',
            height : '250px'
         }, 1000);
    }
});

Here's a demo: http://jsfiddle.net/bKm4U/

like image 95
AlienWebguy Avatar answered May 18 '26 15:05

AlienWebguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!