recording the "mouseenter" event when the mouse enters the element from within

For an interesting visual representation, check out this fiddle

Don't worry about the CSS for now.

The main objective of this block of jQuery code is to determine the direction opposite to where the mouse initially entered into the .container element. Despite its appearance, just focus on what it's meant to do. Directions are indicated by n (north), ne (northeast), and so forth...

If you open up the developer console and move your mouse crazily within the boundaries of the invisible div.container, you will eventually see 'undefined' printed in the console. (The container surrounds a circular button)

An occurrence of 'undefined' only happens when x === 0 && y === 0 in the getMovementDirection() function. This indicates that the mouse, upon entering div.container, was already inside div.button (the spherical button) - which should not be possible.

Hence, my question is, what's causing this behavior in the code?

-Appreciate any guidance provided

PS: The title could use some work.

jQuery code

(function($) {
    var $container = $('div.container'),
        $button = $('div.button');

    $container.on('mouseenter', function(e) {
        var mouseLocation = {
            x: e.pageX,
            y: e.pageY
        }
        var buttonLocation = {
            x: $button.offset().left,
            y: $button.offset().top
        }

        var loc = getMovementDirection(mouseLocation, buttonLocation, jQuery);
        console.log(loc);
    });
})(jQuery);

function getMovementDirection (mouse, container, $) {
    var width = $('div.button').outerWidth(),
        height = $('div.button').outerHeight();
    var x, y;

    if (mouse.x < container.x) { x = -1; }
    else if (mouse.x < container.x + width) { x = 0; }
    else { x = 1; }

    if (mouse.y < container.y)  { y = -1; }
    else if (mouse.y < container.y + width) { y = 0; }
    else { y = 1; }

         if ( x === -1 && y === -1 ) { return 'se'; }
    else if ( x ===  0 && y === -1 ) { return 's';  }
    else if ( x ===  1 && y === -1 ) { return 'sw'; }
    else if ( x === -1 && y ===  0 ) { return 'e';  }
    // x === 0 && y === 0 is forbidden
    else if ( x ===  1 && y ===  0 ) { return 'w';  }
    else if ( x === -1 && y ===  1 ) { return 'ne'; }
    else if ( x ===  0 && y ===  1 ) { return 'n';  }
    else if ( x ===  1 && y ===  1 ) { return 'nw'; }
}

Answer №1

My solution may not be the most elegant or even the fix, but I made some updates in the fiddle with a different approach to extract mouse data:

Check out the updated fiddle here

Instead of using jQuery's built-in mouseenter event, I utilized the JavaScript native mouseover event and excluded the button from triggering it. I thought there might be unnecessary overhead in how jQuery handles it (I didn't analyze the code), so I simplified it to a more basic form. Additionally, I borrowed the addevent code from this resource: http://ejohn.org/projects/flexible-javascript-events/

addEvent( $container[0], 'mouseover', function (e) {
    if (e.target === $button[0])
        return;

    // Obtain event details here

    var loc = getMovementDirection(mouseLocation, buttonLocation, jQuery);

    // For debugging
    if (loc != undefined) {
        var width = $('div.button').outerWidth(),
            height = $('div.button').outerHeight();
        console.log(mouseLocation.x, mouseLocation.y, buttonLocation.x, buttonLocation.y, width, height);
        console.log(loc);
    } else {
        console.log("wut");            
    }

I couldn't trigger the "wut" output at all, maybe I'm not quick enough

Update

This is the jQuery code that triggers on every mouseover event to execute the mouseenter behavior

// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
    mouseenter: "mouseover",
    mouseleave: "mouseout"
}, function( orig, fix ) {
    jQuery.event.special[ orig ] = {
        delegateType: fix,
        bindType: fix,

        handle: function( event ) {
            var ret,
                target = this,
                related = event.relatedTarget,
                handleObj = event.handleObj;

            // For mousenter/leave call the handler if related is outside the target.
            // NB: No relatedTarget if the mouse left/entered the browser window
            if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
                event.type = handleObj.origType;
                ret = handleObj.handler.apply( this, arguments );
                event.type = fix;
            }
            return ret;
        }
    };
});

There might be a delay due to rerunning handling code on a different element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a Radial/Pie Menu using CSS3: A Step-by-Step Guide

I am interested in creating a radial menu using CSS3 transforms animations, similar to the example shown on this Wikipedia page or the flash version demonstrated on this website. Although there is a jQuery implementation available using canvas called Radme ...

Problem encountered with submenu text in CSS drop-down menu

Hey there! I've recently started working on a website and encountered a problem while trying to create a dropdown menu using CSS and HTML. The hover function for the submenu is functioning properly, but I'm struggling with changing the font color ...

The iPhone touch functionality is mimicking hover behavior within an HTML5 application

I am creating an HTML5 application using Bootstrap. I have implemented some custom markup to style radio buttons, as well as included JQuery for functionality: <div role="group" class="btn-group btn-group-justified"> <label for="radioOption1" ...

What steps should be followed to retrieve a tagged photo from Instagram?

I used the code below to retrieve an Instagram photo, but it turns out that the photo I received is not what I was looking for. Can anyone offer some assistance with this issue? <div class="instafeed"></div> <script type="text/javascript"&g ...

Whenever I click on a hyperlink, IE7 shifts the position of my navigation

My navigation is positioned absolutely to its relative parent. Although I used some hacks to make it work in IE7 and IE8, it's still not as smooth as the CSS3 code I used for FF/Chrome and Opera. The issue arises when clicking on an anchor in the menu ...

Using AngularJS service to perform a JQuery ajax request

$scope.results = searchService.CallWeb($scope.userName); In my AngularJS controller, I have the code snippet mentioned above. The function searchService.CallWeb() belongs to an AngularJS service that performs a jQuery AJAX request. Although the jQuery AJA ...

jQuery Shutter taking over the entire document (Camera-style Animation)

I found this example to create a Camera Shutter Effect: Check it out here I want to apply this effect to cover the entire document (100% width and 100% height), but how can I achieve that? Setting var container = $('body'); doesn't make th ...

Issues with responsive CSS on mobile devices

I am experiencing an issue with responsiveness on my website - there is too much empty space between the element and the end of the window when viewed on a mobile phone. I have added the following code to my document in the head section: <meta name="vi ...

The Ajax request returns a 200OK status code indicating success, yet the response payload is missing

Recently, I attempted to utilize a basic password strength-checking service. However, despite receiving a successful ajax call with a 200OK response status, the response body was empty. The error callback provided below was triggered instead: var password ...

How to add icons to HTML select options using Angular

Looking for a way to enhance my component that displays a list of accounts with not only the account number, but also the currency represented by an icon or image of a country flag. Here is my current component setup: <select name="drpAccounts" class= ...

The required field validator's text property may stop displaying, but the error message will still show up in the validation summary

I am encountering an issue with a RequiredFieldValidator's text property. In my ASP web form, I have a Panel where I create a table with a textbox and a RequiredFieldValidator during the overridden OnPreInit event. This table is then stored in a sessi ...

What could be causing the HTML content to not display when the code is executed?

I've recently started using Visual Studio Code for my project. I am able to build my code without any errors, but when I run it, the HTML content does not display properly - only the CSS styling for the header and footer is visible. I have tried click ...

What is the best way to activate a jQuery function during an AJAX request?

Have a question concerning jQuery? I am working on an ajax function that triggers a click event after successful execution: var rowdiv = '#DiamondSetting'; $(rowdiv).hide(); $.ajax({ type: "post", ...

The CSS and Javascript files are failing to load

My web page is not displaying my CSS and JavaScript properly when I access it through a folder in the browser. Both files are located within multiple subfolders. I have attempted to rename the files to troubleshoot the issue. <head> <link rel=" ...

Utilizing @mixin for implementing right-to-left (RTL) support in Angular applications

I have incorporated a mixin in my Angular app to facilitate the conversion from LTR to RTL. @mixin rtl($property, $ltr-value, $rtl-value) { [dir='ltr'] & { #{$property}: $ltr-value; } [dir='rtl'] & { #{$property}: ...

Troubleshooting: Date picker malfunction in ASP.NET web form with jQuery

I have been struggling to get the date picker working in my asp.net web form. I have tried changing the code multiple times, testing with other examples, and even creating a new page for testing, but it still isn't functioning properly. <%@ Page L ...

Replace text using the str_replace function

I have a total of seven lines of text that I need to manipulate using PHP. My first task is to filter out any lines that do not contain the word 'MARCO1998'. Next, from the remaining lines, I need to extract only the 1-3 numbers that come after ...

Locate the unordered list if its immediate parent is a list item

Here is the HTML code snippet I am working with: <div class="nav-collapse collapse"> <ul class="nav"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret">< ...

Confirm Email Address Using AJAX and PHP

I am struggling with submitting my form and using an AJAX call to send the data to a PHP file. The PHP file contains email validation using filter_var, and if the validation returns false, the response should be sent back to Javascript. The validation part ...

Tips for locating a `<li>` element using its data-rel attribute and corresponding value in jQuery

Is there a way to locate an li element that contains a data-rel attribute with the value of "a1"? <li class="thumbImg" data-rel="a1"> <img src="img/a0.jpg" width='150' height="80"> </li> var relValue = "a1"; $('li[dat ...