Highlighting HTML table row on hover by making it wider than the table itself

Tables are great for displaying structured data. They might have been used for odd tasks as positioning images or even making websites grids but these days HTML tables are used mostly for its original purpose. One of the things we can do if we want our records displayed in this format more fun to play around with is to add some row highlight effect. There are variety of effects that we could apply but I think one of the most useful from the UX perspective is to emphasize the data that we currently hover over.

Simple table row emphasis

So let’s start with basic table and some styling:

<body>
  <table>
    <tbody>
  <tr>
    <td>John</td>
    <td>Bar</td>
    <td>34</td>
    <td>programmer</td>
  </tr>
  <tr>
    <td>Ann</td>
    <td>Foo</td>
    <td>28</td>
    <td>teacher</td>
  </tr>
  <tr>
    <td>John</td>
    <td>Bar</td>
    <td>34</td>
    <td>programmer</td>
  </tr>
        <tr>
    <td>Ann</td>
    <td>Foo</td>
    <td>28</td>
    <td>teacher</td>
  </tr>
  </tbody>
    </table>
</body>
body {
  width:100vw;
  background-color:grey;
}
table {
  width:70%;
  margin:100px auto;
  background-color: white;
  border-collapse: collapse; 
}
td {
  text-align:center;
  padding: 20px;
}
tr {
  border: 1px solid transparent;
}
tr:hover td{
  cursor:pointer;
  color:red;
  border-top: 1px solid grey;
  border-bottom: 1px solid grey;
}

tr:first-child:hover td {
  border-top: none;
}
tr:last-child:hover td {
  border-bottom: none;
}

It is very basic indeed. So we have a hover effect on a row when we add borders in hovered row and change its text color. Some transparent borders and special styling for the first and last row have been used to prevent annoying 1px layout jumps on row change.

See the Pen Table row highlight by codeVerses (@codeVerses) on CodePen.

To make it look better we could add some extra styling of course, but what about making the selected row stand out by slightly extending it beyond the table width? Well it is not that straight forward. We cannot use width manipulation as the table would not render anything outside of its body. The other option would be to use the scaleX transformation. This would allow us to beat the table borders but it has very bad downside to it. Scaling would make all the row children scale too, including their inner text causing nasty blur to the contents. So we would have to be more creative than that.

Using empty table cells and scale to achieve desired effect

We need to add additional empty cells and put divs in there that we will scale on row hover so the text contents are not affected. This would be our row in html:

<tr>
    <td class="highlight"><div></div></td>
    <td>Ann</td>
    <td>Foo</td>
    <td>28</td>
    <td>teacher</td>
    <td class="highlight"><div></div></td>
  </tr>

And our new css covers the scaling and additional stuff like smoother transition, border radius and adding some box shadow to make it look better.

td.highlight {
  padding:0;
  width:4px;
}
td.highlight div {
  width:4px;
  height:60px;
  border-radius:4px;
  background-color: white;
  transition: all 0.2s ease-in-out;
}
tr:hover {
 box-shadow: 0px 9px 4px -6px grey;
}
tr:hover td.highlight div {
  transform: scaleX(3);
}

Wow, we finally broke through the table width frontier and our row is expanding nicely beyond the table body. Here is the complete example:

See the Pen Table row highlight make row wider than table by codeVerses (@codeVerses) on CodePen.

Easy JavaScript array de-duplication

Getting rid of duplicate values in a list/array is quite a common software development task. I remember in the past when I first faced this problem it was not very straight forward to do it in vanilla JS. You would think that such a common operation would be handled with out of the box method or command but somehow it was not included in the older Ecma Script specifications.

The old ES5 method

So to achieve desired results your best bet was using combined array.filter and array.sort or similar approach. One that would need to iterate over the whole list of values and get rid of duplicates one entry after another. Something along these lines of code:

function uniq(array) {
    return array.sort().filter(function(item, pos, arr) {
        return !pos || item != arr[pos - 1];
    })
}

So what used to happen here was we were sorting the array first and then compare each item with its predecessor to see if they differ and remove item if they do not. Obviously this would work with primitive values only as array.sort does not put objects in order as they appear all the same to this method. Handling object values would require even more code so lot of people turned to methods provided by 3rd party libs like lodash or jQuery which offered much easier ways to do the list clean up.

Modern ES6/7 array de-duplication

Luckily for us front end developers ES6 update brought us many new functionalities and data types. We can now de-duplicate arrays (or any other lists) with this neat one liner:

uniqueOnly = [...new Set(array)];

We use the Set type which by definition is a list of unique items so if we pass an array into its constructor it does old the hard work of making sure all the values that end up in the created set are unique. It does it equally well for both primitives and more advanced data types like objects. Then we use another new functionality – the spread operator (…) to assign this newly created set back to an array. This makes de-duplicating arrays in modern js much easier and fun.

Tilting images with phone’s gyroscope the javascript way

Have you ever seen website UI reacting to device’s orientation? If not then maybe it is time to browse a little, there are some really cool effects that you can achieve by triggering visual changes with device motion. Let’s dive into a case of making images tilt while we angle our phone.

Detecting mobile device orientation

These days increasing number of mobile browsers support DeviceOrientationEvent which gives us the data we need about current device orientation. For the purpose of this task we need only one property that this event object – DeviceOrientationEvent.gamma. It is a number that represents the device’s motion around the y axis so simply speaking its left to right rotation. Its value ranges from -90 to 90. We can listen to that event on the window object like this:

window.addEventListener("deviceorientation", function(event) {
console.log(event.gamma);
});

If you look at the returned value you will notice that it is super accurate, covering lot of decimal spaces and reacting to even slightest device movements. We do not need this to be so precise (actually we do not want it) so we can use the Math.round method to round it to the nearest integer which will be handy when we will use this data to animate the image.

window.addEventListener("deviceorientation", function(event) {
let position = Math.round(event.gamma);
});

Setting up image tilt CSS transformation

OK, so we receive our client’s Y-axis angle, now it’s time to set up some initial css and html. We will have our image wrapped to set some perspective and we need to set the transition property to achieve smoother transform animations, which we will use to animate our element with. The basic HTML/CSS setup would look like this:

<body>
  <div class="wrapper">
      <img id="tiltable" src="http://i64.tinypic.com/2cpte9f.jpg"/>
  </div>
</body>
body {
  width:100%;
  height:100vh;
  display:flex;
  justify-content:center;
  align-items:center;
  background-color:black;
 } 

.wrapper {
  perspective: 15px;
}

#tiltable {
  height:400px;
  transition: transform 0.5s;
  backface-visibility: hidden;
}

Triggering animation when device orientation changes

Now it’s time to connect the dots and make sure our event triggers the animation. Let’s go back to our event handler and throw in some code.

const inner = document.getElementById("inner");
const limit = 45;

window.addEventListener("deviceorientation", function(event) {
let position = Math.round(event.gamma);
 if (Math.abs(position) > limit) {
       if (position > limit) {
            position = limit;
        } else {
            position = -limit;
            }
        }
position = position / -100;
let style = "rotateY(" + position + "deg)";
inner.style.transform = style;
});

As you can see I included some additional stuff, first there is this if else statement which limits the position value for both positive and negative number scenario. This is to set out limits to element css rotation degree which we will use to animate the image. Next we transform the position variable by dividing it by -100 to rotate by fractions of deg only and in opposite direction than the device angle to achieve desired visual effect. Finally we assign value to our style variable which uses the position variable to construct the css property value for transform property of the element we want to rotate which we then use to set this property via element.style property of our selected HTML element.

Making things smoother

Well we are almost there but things are still a bit rough on the edges. We would like our animation not to be triggered every single time the device changes its orientation. We can achieve this by implementing simple counter function which will limit the animation to be triggered every n-th time the event fires only, every 10th time in our case. You can find complete, working example below on the embeded codepen.

See the Pen
Tilting images with device orientation
by codeVerses (@codeVerses)
on CodePen.