0

How do you get the location of a mouse and then place a HTML element beside it?
For example, If i have a <textarea> and i want a toolbar to appear by the mouse when it is hovered over, how would i do this?

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Jacob G
  • 13,762
  • 3
  • 47
  • 67
  • http://craigsworks.com/projects/qtip/ – adeneo May 11 '14 at 20:18
  • Where is your code? Or do you expect us to just do work for you? – Giacomo1968 May 11 '14 at 20:26
  • @JakeGould, I was going to post my code but all i was really looking for was the attributes needed to get the position so i decided my coding was not needed. But, jqueryrocks gave me everything i needed. – Jacob G May 11 '14 at 20:37

3 Answers3

5

You can get the x and y coordinates with event.pageX and event.pageY in your mousemove function for the textarea.

$('textarea#myText').mouseenter(function(event) {
  $('#toolbar').show();
});
$('textarea#myText').mousemove(function(event) {
  var left = event.pageX + 20;
  var top = event.pageY + 20;
  $('#toolbar').css('left', left).css('top', top);
});
$('textarea#myText').mouseleave(function(event) {
  $('#toolbar').hide();
});
2

The answer can be found here: HTML-Tooltip position relative to mouse pointer

Look at this jsFiddle for more info.

var tooltips = document.querySelectorAll('.tooltip span');

window.onmousemove = function (e) {
    var x = (e.clientX + 20) + 'px',
        y = (e.clientY + 20) + 'px';

    for (var i = 0; i < tooltips.length; i++) {
        tooltips[i].style.top = y;
        tooltips[i].style.left = x;
    }
};
Community
  • 1
  • 1
1

What about this?

http://jsfiddle.net/TL7V7/5/

yourText = document.getElementById('yourText');
yourToolbar = document.getElementById('yourToolbar');
yourText.addEventListener('mouseenter',function(e){
    setTimeout(function(){
        yourToolbar.style.opacity=opacity_hi;
        //this CSS3 renders faster:
        yourToolbar.style.transform='translate('+(1000+mx-10)+'px,'+(1000+my+10)+'px)';
        yourToolbar.style.webkitTransform='translate('+(1000+mx-10)+'px,'+(1000+my+10)+'px)';
    },hide_delay/2);
    //...
});
yourText.addEventListener('mousemove',function(e){
    mx=e.pageX;
    my=e.pageY;
    //...
});

See the link above.

Matteo T.
  • 1,278
  • 11
  • 13
  • Thank you as well! This is why i love Stack Overflow. You get so many great answers so quickly! – Jacob G May 11 '14 at 21:49