Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I dynamically add text next to the mouse cursor via javascript?

Tags:

javascript

css

Right now I changed the cursor image if any ajax is in a process using this javascript code

$(function(){  
  $("html").bind("ajaxStart", function(){  
     $(this).addClass('busy');  
   }).bind("ajaxStop", function(){  
     $(this).removeClass('busy');  
   });  
});

and below css

    html.busy, html.busy * {  
        cursor: wait !important;  
    } 

Now I want to add some text next to the cursor too. And remove it when the ajax finishes. How is that possible without using any jQuery plugin?

like image 204
Radek Avatar asked Aug 14 '12 02:08

Radek


3 Answers

Try this:

Demo with start / stop functions and changing text

http://jsfiddle.net/SY4mv/18/

like image 70
PitaJ Avatar answered Sep 27 '22 17:09

PitaJ


See http://jsfiddle.net/PbAjt/show/:

CSS:

#cursorText{
    position:absolute;
    border:1px solid blue; /* You can remove it*/
}

JavaScript:

document.body.onmousemove=moveCursor;
var curTxt=document.createElement('div');
curTxt.id="cursorText";
curTxt.innerHTML="Hello!"; /* Or whatever you want */
document.body.appendChild(curTxt);
var curTxtLen=[curTxt.offsetWidth,curTxt.offsetHeight];
function moveCursor(e){
    if(!e){e=window.event;}
    curTxt.style.left=e.clientX-curTxtLen[0]+'px';
    curTxt.style.top=e.clientY-curTxtLen[1]+'px';
}

Depending on what you want you can change

curTxt.style.left=e.clientX-curTxtLen[0]+'px';

into

curTxt.style.left=e.clientX+'px';

and

curTxt.style.top=e.clientY-curTxtLen[1]+'px';

to

curTxt.style.top=e.clientY+'px';
like image 37
Oriol Avatar answered Sep 27 '22 17:09

Oriol


CSS:

#tooltip {
    position: fixed;
    background-color: black;
    color: white;
    padding: 2px;
    opacity: 0;
    -webkit-border-radius: 3px;    
    border-radius: 3px;
    -webkit-transition: opacity 0.3s ease-in-out;
    -moz-transition: opacity 0.3s ease-in-out;
    -ms-transition: opacity 0.3s ease-in-out;
    -o-transition: opacity 0.3s ease-in-out;
    transition: opacity 0.3s ease-in-out;
}

html.busy #tooltip { opacity: 1 }

html.busy, html.busy * {  
        cursor: wait !important;  
    }

HTML:

<div id="tooltip">Message</div>

JS:

$(function() {
    $("html").bind("ajaxStart", function() {
        $(this).addClass('busy');
        $(this).bind('mousemove', function(event) {
            $('#tooltip').css({
                top: event.pageY - $('#tooltip').height() - 5,
                left: event.pageX
            });
        });
    }).bind("ajaxStop", function() {
        $(this).removeClass('busy');
        $(this).unbind('mousemove');
    });
});

Event DOC: http://api.jquery.com/mousemove/ ​

DEMO: http://jsfiddle.net/RGNCq/1/

like image 42
Oswaldo Acauan Avatar answered Sep 27 '22 17:09

Oswaldo Acauan