Subscribe to our RSS

Create Custom Cursors without .cur File

Tags: , ,

Create Custom Cursors without .cur File

Sometimes you may want to replace your cursor with a custom image or use a custom image to move with your cursor. This quick JavaScript tutorial will show you how to implement it.
The task is pretty simple. At first we should hide the default cursor for the section where we will display our custom one. Our custom cursor will actually be a DIV with an image on the background. We will use JavaScript to change the position of this DIV when the user moves the mouse over the section.

The markup

<div id="test-area">
     Move mouse over this area.
</div>
<div id="mycursor"></div>

The #test-area will be the section with our custom cursor to appear and the #mycursor will be the actual DIV with the custom cursor image. Here are a few lines of CSS code to stylize the markup:

#test-area {
     height: 200px;
     border: 3px dashed #CCCCCC;
     background: #FFFFFF;
     padding: 20px;
     cursor: url(./blank.cur), none;
}
#mycursor {
     cursor: none;
     width: 97px;
     height: 137px;
     background: url("/article-sources/images/pointer-cursor.gif") no-repeat left top;
     position: absolute;
     display: none;
     top: 0;
     left: 0;
     z-index: 10000;
}

The code (we hope) is crystal clear but let’s stop to review one aspect. In the #test-area you see the ‘cursor: …’ declaration. We will use this to hide the default browser cursor. The easiest way to do so is to load a blank cursor (you may download it here), but this unfortunately will not work in Chrome & Opera. It will display a black rectangle in Chrome and a default pointer cursor in Opera. But since this tutorial covers other important aspects related to cursor behavior (such as how to handle mouse movement, etc.), it is still a useful topic to cover for those just starting to learn JavaScript programming. So, let’s continue ;).

The finishing part is to add a few lines of JavaScript code for jQuery to make our arrow follow the cursor.

<script type="text/javascript">
     $(document).ready(function(){
          $('#test-area').mouseout(function(){
               $('#mycursor').hide();
               return >false;
          });
          $('#test-area').mouseenter(function(){
               $('#mycursor').show();
               return >false;
          });
          $('#test-area').mousemove(function(e){
               $('#mycursor').css('left', e.clientX - 20).css('top', e.clientY + 7);
          });
});
</script>

That’s it ;) Click the Demo button to view it in action.

Leave a comment

Your name

March 18, 2010

Spam protection. Enter letters you see in the box below.