4

I need to change the color of a table cell when the mouse hovers over the left-most 10 pixels of the cell. Currently I have this:

$("#myTable table thead tr th:nth-child(3)").mouseover(function () {
    $(this).css("background-color", "red");
});
$("#myTable table thead tr th:nth-child(3)").mouseout(function () {
    $(this).css("background-color", "white");
});

This works for hovering over the whole element, but I need it to only happen when hovering over the left-most 10px of it.

Keavon
  • 6,837
  • 9
  • 51
  • 79
  • 2
    Can you just add a div 10px wide to the left side of the cell and target that on the mouseover instead? – hiattp Oct 12 '13 at 18:40

2 Answers2

4

You could use mousemove instead and check offset coordinates:

$("div").on({
    mousemove: function (e) {        
        var $this = $(this);
        var x = e.offsetX;
        
        // fix for firefox
        if(typeof x === "undefined"){
           x = e.pageX - $this.offset().left;     
        }        
        
        $this.css("background-color", x <= 10 ? "red" : "white");
    },
    mouseleave: function (e) {
        $(this).css("background-color", "white");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>test test test test</div>
canon
  • 40,609
  • 10
  • 73
  • 97
1

Put a div 10px wide to the left side and target that for the mouseover:

HTML

<th>
  <div class="hover-target"></div>
  <p>Name</p>
</th>

JS

$(function () {
  $("#myTable thead tr .hover-target").mouseover(function () {
    $(this).parent().css("background-color", "red");
  });
  $("#myTable thead tr .hover-target").mouseout(function () {
    $(this).parent().css("background-color", "white");
  });
});

http://jsfiddle.net/FDRm8/

hiattp
  • 2,326
  • 1
  • 20
  • 23
  • Visual Studio gives me the warning: `Validation (HTML5): Element 'div' cannot be nested within element 'th'.` – Keavon Oct 12 '13 at 18:56
  • Really? I'm not aware of a reason as to why it's not valid. Does it cite a source for the validation error? – David Thomas Oct 12 '13 at 18:57
  • Are you using an old version? See: http://connect.microsoft.com/VisualStudio/feedback/details/762026/html5-validator-incorrectly-disallows-div-within-th – hiattp Oct 12 '13 at 18:59