Skip to content Skip to sidebar Skip to footer

Changing CSS URL For Pointer Cursor (using Javascript)

I asked a question yesterday here about having a cursor that changes regularly using javascript, to make it look animated. I got a great answer (Thank you Shiva!). I've now been tr

Solution 1:

You can try using jQuery for this :

var images = [
  'assets/shared/cursors/point1.cur',
  'assets/shared/cursors/point2.cur',
  'assets/shared/cursors/point3.cur',
  'assets/shared/cursors/point4.cur'
];

var x = 0;

function changeLinkCursorHoverBinding(){
  $("a").hover(function(){/*this is the mouseenter triggered function*/
    $(this).css("cursor",'url("' + images[x] + '"), default');
  }, function(){
    //handle mouseleave here if needed
  });

  x = (x === images.length - 1) ? 0 : x + 1;//put at the end to start at 0

  setTimeout(changeLinkCursorHoverBinding, 250);
}

$(document).ready(changeLinkCursorHoverBinding);//initial call of the function

EDIT

Or without jQuery :

var images = [
  'assets/shared/cursors/point1.cur',
  'assets/shared/cursors/point2.cur',
  'assets/shared/cursors/point3.cur',
  'assets/shared/cursors/point4.cur'
];

var x = 0;

function changeLinkCursorHoverBinding(){
 var elems = document.querySelectorAll("a");
 elems.removeEventListener("mouseenter", onHover);
 elems.removeEventListener("mouseleave", offHover);

 elems.addEventListener("mouseenter", onHover);
 elems.addEventListener("mouseleave", offHover);

 x = (x === images.length - 1) ? 0 : x+1;

 setTimeout(changeLinkCursorHoverBinding, 250);
}

function onHover(){
  var elems = document.querySelectorAll("a");
  for(e in elems){
    e.style.cursor = "url('" + images[x] + "'), default";
  }//you can use the regular for loop here if you wanna
}

function offHover(){
  var elems = document.querySelectorAll("a");
  for(e in elems){
    /*handle mouseleave here*/
  }
}

I had to name EH functions (and remove EH each call) because I wasn't sure that addEventListener overrides same handler if called again.

EDIT

for non jQuery way, you need to add onload="changeLinkCursorHoverBinding()" on your <body> tag this way : <body onload="changeLinkCursorHoverBinding()"> (the initial call after page's load).


Post a Comment for "Changing CSS URL For Pointer Cursor (using Javascript)"