Njinx Njinx - 7 months ago 17
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');

});
});
});
}(jQuery));


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

$('document').ready(function() {
$('body').dynamicCursors();
});

var cursorImage = 'generic.cur';


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

Answer

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');
    });
  };
}(jQuery));

And you can call it like so:

$('body').dynamicCursors('generic.cur')

Alternative

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:

$(this).addClass('cursor-generic');

Hope that helps!