views:

43

answers:

3

Hello! Is there a way (using javascript/jQuery) to do following:

On my page, I have one input type=text. This input has a background-image on its right side.

<input id="my-input" type="text" value="foobar" style="background-image:url(path/to/my/image.gif); background-position:right center; background-repeat:no-repeat; height:17px; width:97px;"/>

When the cursor moves over the background-image (width:21px), the cursor icon should be set to pointer. Otherwise it should be cursor:text.

I have to use the input! I am not able to create a new div next to the input for this icon!

I tried to solve this problem like this:

$('#my-input').mousemove(function (event) {
    this.style.cursor = ((event.offsetX || event.layerX) < this.offsetWidth - 21) ? "text" : "pointer";
});

But this won't work. this.offsetWidth - 21 has the right value but event.layerX and event.offsetX is undefined.

Do you have another idea, how to solve this problem? Can you tell me, why my js won't work as I want it to do?

A: 

Mouse position is one of those problems I always look up. Here is one solution. Notice in particular that halfway down is a snippet that shows how to determine the mouse position relative to the upper left corner of the object in question (e.g. a text field). That may be relevant to solving your problem.

Maybe something like the following would work

$('#my-input').mousemove(function(e) {
    var pos = e.pageX - this.offsetLeft;
    this.style.cursor = (pos < this.offsetWidth - 21) ? 'text' : 'pointer';
});
TNi
+2  A: 

I tried this way and its working (tested on IE). Check out here.

$('#my-input').mousemove(function (event) { 

  $(this).css("cursor", ((event.offsetX || event.layerX) < this.offsetWidth - 21) ? "text" : "pointer");

 }); 
Krunal
The OP's given code is also working... read my comment below the OP's post..
Reigel
you are right. this is working.so, I have to look for my error in my other code.
Newbie
A: 

Sounds tough to me.

First at all, the event property offsetX / Y is not cross-browser available. That might be the reason why it is undefined for you.

Your best shot is maybe to check the elements offset using jQuerys .offset() method. Doing some math you might figure out where the cursor is at, bringing event.pageX and event.pageY into play.

Reference: .offset(), events

jAndy