Search code examples
jquerymouseenter

Mouse over fire key press event


I have the following html

 <div class="divcontainer" id="divcontainer1" data-element="1">
   <div class="innerdivcontainer hidden" id="innerdivcontainer1"></div>
 </div>
 <div class="divcontainer" id="divcontainer2" data-element="2">
   <div class="innerdivcontainer hidden" id="innerdivcontainer2"></div>
 </div>
 <div class="divcontainer" id="divcontainer3" data-element="3">
   <div class="innerdivcontainer hidden" id="innerdivcontainer3"></div>
 </div>

I want a function that fires when the mouse is over div container and a user begin to type on his keyboard. The function would change the class innerdivcontainer to not hidden only if the user is hovering over divcontainer and begins to type. I want to use .on because I have new elements loaded into the dom which should also work

I'm thinking something along these lines

 //check for mouse over event
   $('.divcontainer').on({
        mouseenter: function () {
     var data-element = $(this).attr('data-element').
               //check if user begins to type something with if statement
                   if(//code goes here){
                       $('innerdivcontainer'+data-element).show();

                     }

        }
   });

I don't know what to use to check for a key stroke on the keyboard


Solution

  • I don't know if that is really what you are looking for but here is a jsFiddle. I find the result cool but maybe not very user-friendly. Think about adding hover style to your div, to explain to your users how to use your comment section.

    There are several things to note about my implementation :

    First, the use tabindex in the HTML markup to be able to trigger keypress on a div. (Refer to this post). Aside of this, the markup is the same as yours.
    The use of focus and blur to trigger the keypress event on the right div (the one hovered by the mouse).
    And the mouseleave to clear the keypress handler when you leave the div, so the comment section won't appear when you're hovering another div)

    $('.divcontainer').mouseenter(function () {
        var data_element = $(this).attr('data-element');
        $(this).focus();
        $(this).on("keypress", function() {
            $('#innerdivcontainer' + data_element).show();
        });
    }).mouseleave(function(){
        $(this).blur();
        $(this).on("keypress", function(){});
    });
    

    Please tell me if this helps you in any way.