Njinx Njinx - 2 years ago 109
Javascript Question

How to set css cursor value to variable within jQuery?

I am trying to make a little jQuery plugin so I can dynamically change the cursor. But when I try and set the cursor to a variable it doesn't do anything.

Here's the code in the JS file:

(function ($) {
$.fn.dynamicCursors = function () {
this.each(function () {

var cursorImage = null;
$(this).css('cursor', 'url(' + cursorImage + '),auto');


And here's the code for the code within the
tag in the HTML file:

$('document').ready(function() {

var cursorImage = 'generic.cur';

If anyone needs anymore information please let me know. Thanks!

Answer Source

It seems you're setting the cursorImage to null before you set the style attribute. Also, you've got imbalanced parentheses.

Try passing the cursor URL as a parameter to the function:

(function ($) {
  $.fn.dynamicCursors = function (cursorImage) {
    this.each(function () {
      $(this).css('cursor', 'url(' + cursorImage + '),auto');

And you can call it like so:



If you know all the cursors you're going to use, you can use classes:

/* CSS */
.cursor-generic {
  cursor: url('generic.cur'), auto;

So you can just:


Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download