jQuery: spotlight effect

In this post I'm going to show you how to create a nice spotlight effect using jQuery and the CSS3 properties text-shadow and box-shadow. These properties will be used dynamically together with the mouse coordinates of the mousemove event. We start with a basic markup like this:

<h1>Test<span></span></h1>

A couple of CSS styles:

h1 {
 margin: 0.5em;
 padding: 0.5em;
 font: normal 4em "Arial Black", Arial, sans-serif;
 width: 300px;
 height: 300px;
 line-height: 300px;
 background: #000;
 color: #fff;
 text-align: center;
 text-shadow: 0 0 0 #ffc;
 cursor: pointer;
 position: relative;
}

h1 span {
 width: 160px;
 height: 160px;
 position: absolute;
 top: 50%;
 left: 50%;
 margin: -80px 0 0 -80px;
 box-shadow: 0 0 0 #ffc;
 border-radius: 12px;
}

Now with jQuery we need to constantly update the x and y coordinates of the text-shadow and box-shadow properties while the mouse is moving:

$(function() {
  
  var factor = 6;

  $('h1').mousemove(function(event) {
  
    var x = event.clientX - $(this).width();
    var y = event.clientY - $(this).height();
    
    $(this).css('textShadow', x + 'px' + ' ' +  y + 'px' + ' ' +  factor + 'px' + ' ' +  '#ffc').
    find('span').css('boxShadow',    x + 'px' + ' ' +  y + 'px' + ' ' +  factor + 'px' + ' ' + '#ffc');
  
  
  });

});

You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

2 thoughts on “jQuery: spotlight effect”

  1. It's my fault. I forgot to mention that the CSS3 properties used there are not supported by IE8 and lower. However, a simple solution would be using a background image to mimic the spotlight that here is achieved with the box-shadow property. You change dynamically the background-position property or you can set it on an element that you move around with the mouse. For the text-shadow, instead, simply duplicate the text content of the h1 element using another span element and then move this element around. HTH :-)

Leave a Reply

Note: Only a member of this blog may post a comment.