user4312749
user4312749

Reputation:

JS Event CTRL + mouse over + hide text

I have to achieve this:

  1. Hide text in a div
  2. User will press Ctrl key, then put his mouse over a button - a javascript function has to be called, and the text in the div should be displayed
  3. If the User releases the Ctrl key - the text should disappear (even if the mouse is on the button), similarly if the User moves the mouse out from the button - the text should disappear (even if the Ctrl key is pressed)

My work so far:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
    loadHandler = function(){
        $("#selector").mouseover(function(e){
            if(e.ctrlKey) {
                //what do I have to write here so that holding CTRL will be recognized ?
            }
        });
    }
</script>
</head>

<body onload="loadHandler();">
<button type="button" onmouseover="document.getElementById('center').style.visibility = 'visible'">CTRL+mouseover</button>
<div id="center" onmouseout="this.style.visibility = 'hidden'">
        <h1>Text text text</h1>
</div>
</body>

</html>

Link

I have to admit that I just started to learn JS so please help me out :)

Upvotes: 0

Views: 685

Answers (2)

hoogw
hoogw

Reputation: 5525

Working sample,

MouseEvent.shiftKey, MouseEvent.ctrlKey

MouseEvent.ctrlKey

MouseEvent.shiftKey

   <img onmouseover="keypress_test(event)" onmouseout="keypress_test(event)">


    function keypress_test(event) {

             // false, no press, 
             // true, pressed

              console.log(event.ctrlKey)

              console.log(event.shiftKey)


             if (event.ctrlKey) {

                    // hide text
                }
       }

Upvotes: 1

void
void

Reputation: 36703

Perfectly working version

$(document).ready(function(){
    var keyPressed = false;
    var mouseovered = false;
    $("#center").mouseover(function(e){
      doStuff();
         mouseovered = true;
    });
    $("#center").mouseout(function(){
        doStuff();
        mouseovered = false; 
    });
    $(document).keydown(function(e){
         doStuff();
         if (e.ctrlKey) 
         {
             keyPressed = true;
         }
        else keyPressed = false;
    });

    $(document).keyup(function(e){

         if (keyPressed) 
         {
             keyPressed = false;
         }
        doStuff();
    });

    function doStuff()
    {
        if(mouseovered && keyPressed) $("#center").css({"color": "#000"});
    else  $("#center").css({"color": "#fff"});
    }
});

I just haven't hidden the text by default. Or else It will be hard for yo find where it is currently. And don't forget to click on the body before checking. Else keypress wont be detected.

Working Fiddle

Upvotes: 0

Related Questions