Is it possible to change the cursor with a customized image stored in a variable?
I have tried setAttribute or .style.cursor, but it does not seems to work..
Here are some examples of what I have tried:
var MyImage = MyImage.png;
document.getElementById("DivWithMouseOverEvent").style.cursor = MyImage;
I also tried:
var MyImage = MyImage.png;
document.getElementById("DivWithMouseOverEvent").setAttribute("cursor", MyImage);
The idea is that the var MyImage may change depending on some actions by the user.
I know Firefox requires a second cursor option, but I do not know how to do it with a variable.
CodePudding user response:
This is my example. Hope it can help you
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
</head>
<body>
<h1 id="title">
This is a static template, there is no bundler or bundling involved!
</h1>
<script>
const cursor = "Ball.cur";
const url = `url(${cursor}), auto`;
const title = document.getElementById("title");
title.style.cursor = url;
</script>
</body>
</html>
CodePudding user response:
-------Simply run this code direct to confirm please
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
.cursor{
cursor: wait;
}
div.cursor{
background-color: green;
color: white;
}
</style>
</head>
<body>
<div >
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eos, nobis cupiditate mollitia expedita voluptatibus quas sunt? Voluptatibus neque harum pariatur, laboriosam facere autem dolor reiciendis, quas necessitatibus est, amet quia?
</div>
<script>
$(function () {
$('.cursor').on('mouseenter', function(){
$(this).css({'cursor': "url('https://ani.cursors-4u.net/others/oth-9/oth927.cur'), auto", 'color':'orange', 'padding': '8px'});
})
})
</script>
</body>
</html>
CodePudding user response:
There are a couple of problems with the code given.
The image definition needs to be not only a string, but also a url.
Also, a fallback is mandatory (not just required by Firefox).
See MDN for more detail on what is allowed.
let MyImage = 'https://i.stack.imgur.com/LZ9aI.png';
document.getElementById("DivWithMouseOverEvent").style.cursor = 'url(' MyImage '), grab';
#DivWithMouseOverEvent {
width: 50vw;
height: 50vh;
background: cyan;
}
<div id="DivWithMouseOverEvent"></div>