Change cursor image (CSS URL) using Javascript - javascript

I'm currently updating my website. I wanted to have an animated cursor on one of the pages. I found out that modern browsers don't support the .ani format or animated gifs, so I had the idea that I could use the .ani format for older browsers, and for modern browsers have a .png cursor that changes using javascript.
Here's what I tried:
<!DOCTYPE html>
<html>
<head>
<body background="example.gif">
<style type="text/css" id="cursor"> body {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum3.png'), default;} </style>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("cursor") .body images[x];
}
function startTimer() {
setInterval(displayNextImage, 400);
}
var images = [], x = -1;
images[0] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum1.png'), default;};
images[1] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum2.png'), default;};
images[2] = {cursor: url('assets/shared/cursors/drum.ani'), url('assets/shared/cursors/drum3.png'), default;};
</script>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("test") .src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 400);
}
var images = [], x = -1;
images[0] = "assets/shared/cursors/drum1.png";
images[1] = "assets/shared/cursors/drum2.png";
images[2] = "assets/shared/cursors/drum3.png";
</script>
</head>
<body onload="startTimer()">
<img id=test src="assets/shared/cursors/drum3.png">
<div style="height: 1000px; width: 1000px;"></div>
</body>
</html>
I put the 'test' image in to see if the code worked at all, and sure enough the 'test' image does change as planned, but the cursor just stays at 'drum3.png', not changing. I've tried it many different ways, but can't get it to work.
If possible I'd like to avoid JQuery.
Any help is really appreciated. Thank you!

You can use something like this:
var images = [
'http://lorempixel.com/21/21/',
'http://lorempixel.com/22/22/',
'http://lorempixel.com/23/23/'
];
var x = 0;
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.body.style.cursor = 'url("' + images[x] + '"), default';
}
setInterval(displayNextImage, 400);
html, body {
height: 100%;
}
body {
cursor: url('http://lorempixel.com/20/20/'), default;
}

I couldn't work out how to also have a .ani fallback cursor, so instead I changed my .png files to .cur files, which work in old and new browsers. So, the code ended up looking like this:
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
var images = [
'assets/shared/cursors/drum1.cur',
'assets/shared/cursors/drum2.cur',
'assets/shared/cursors/drum3.cur',
'assets/shared/cursors/drum4.cur'
];
var x = 0;
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.body.style.cursor = 'url("' + images[x] + '"), default';
}
setInterval(displayNextImage, 250);
</script>
<body>
<div style="height: 1000vh; width: 1000vw;"></div>
</body>
</html>
</head>
</html>
Thank you again Shiva. I couldn't have worked this out without you.
I've asked a related, but different question here: Changing CSS URL for pointer cursor (using Javascript)

Related

how to change a text and image every 5 seconds in javascript and html

hey I wrote a JavaScript code and I managed to make the image change every few seconds but the text is changing alongside with the image but not the correct text is shown here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<style>
img{
height: 500px;
width: 450px;
}
h1{
color: darkgreen;
margin-top: 20px;
font-family: Comic Sans MS, cursive, sans-serif;
}
.button{
margin-left: 45%;
}
</style>
<script>
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
setTimeout("changeImage()", 6000);
}
function changeText() {
var txt= document.getElementById("message");
txt.textContent = text[y];
y++;
if(y>= text.length){
y = 0;
}
setTimeout("changeText()", 6000);
}
var text = [], y=0;
text[0] = "MSG1";
text[1] = "MSG2";
text[1] = "MSG3";
setTimeout("changeText()", 6000);
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 6000);
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h1 id="message">
Hello
</h1>
<img id="img"
src="image1.jpg" >
</div>
<div class="col-md-3"></div>
</div>
</div>
</body>
</html>
is there any efficient way to do it my goal is to make 3-5 images on an html webpage that change between each other every few seconds and each image has a different text above it
Combine your two functions into one, so both things happen at the same time:
<script>
function changeImageAndText() {
var img = document.getElementById("img");
img.src = images[x];
var txt = document.getElementById("message");
txt.textContent = text[x];
x++;
if (x >= images.length) {
x = 0;
}
setTimeout("changeImageAndText()", 6000);
}
var text = [],
images = [],
x = 0;
text[0] = "MSG1";
text[1] = "MSG2";
text[2] = "MSG3";
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImageAndText()", 6000);
</script>
Instead of maintaining two arrays have one array of objects each of which contains image and text information. You can then create markup containing both sets of information at once rather than relying on two functions.
This working example uses images from dummyimage.com.
const data = [
{ image: 'https://dummyimage.com/100x100/666/ff0', text: 'Image 1' },
{ image: 'https://dummyimage.com/100x100/222/ff0', text: 'Image 2' },
{ image: 'https://dummyimage.com/100x100/fff/000', text: 'Image 3' },
{ image: 'https://dummyimage.com/100x100/a45/000', text: 'Image 4' },
];
// Cache the element
const div = document.querySelector('div');
// `carousel` is the main function into which we
// pass the data
function carousel(data) {
// `loop` is what `setTimeout` calls every second
// We initialise `count` to 0
function loop(count = 0) {
// Create the HTML using a template string
const html = `
<figure>
<img src="${data[count].image}" />
<figcaption>${data[count].text}</figcaption>
</figure>`;
// Add the markup to the div
div.innerHTML = html;
// Reset the count if we've reached the
// end of the array, otherwise increment it
if (count === data.length - 1) {
count = 0;
} else {
++count;
}
// Call `loop` every second with the
// updated `count` variable
setTimeout(loop, 1000, count);
}
loop();
}
carousel(data);
<div></div>
Additional information
Template/string literals
querySelectorAll
figure
Your code is basically fine as far as timing goes - with intervals as long as 6 seconds you aren't going to notice if one timeout happens a microsecond after the other.
Your problem is a straightforward bug. There is a repetition of text[1] so the MSG2 never gets shown.
This is your snippet with just that change made and it works perfectly.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<style>
img {
height: 500px;
width: 450px;
}
h1 {
color: darkgreen;
margin-top: 20px;
font-family: Comic Sans MS, cursive, sans-serif;
}
.button {
margin-left: 45%;
}
</style>
<script>
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if (x >= images.length) {
x = 0;
}
setTimeout("changeImage()", 6000);
}
function changeText() {
var txt = document.getElementById("message");
txt.textContent = text[y];
y++;
if (y >= text.length) {
y = 0;
}
setTimeout("changeText()", 6000);
}
var text = [],
y = 0;
text[0] = "MSG1";
text[1] = "MSG2";
text[2] = "MSG3";
setTimeout("changeText()", 6000);
var images = [],
x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 6000);
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<h1 id="message">
Hello
</h1>
<img id="img" src="image1.jpg">
</div>
<div class="col-md-3"></div>
</div>
</div>
</body>
</html>
However, you mention efficiency, and again at such long time intervals it probably isn't going to make a great deal of difference as the JS is only called every 6 seconds but if you want to make more efficient code then consider ditching JS and using CSS animations instead - the browser will have a chance of using the GPU then.
The way I would do it is this:
const text = ["MSG1", "MSG2", "MSG3"];
const image = ["image1.jpg", "image2.jpg", "image3.jpg"];
const imageObj = document.GetElementById("img");
const textObj = document.GetElementById("message");
let counter = 0;
function ChangeImage() {
if (counter == text.length) {
counter = 0;
}
textObj.innerText = text[counter];
imageObj.src = image[counter];
counter++;
}
setInterval(ChangeImage, 3000); // 3000 = 3 Seconds, 5000 = 5 seconds.
The main thing to remember is to reduce the amount of times you repeat yourself, when looping through an array (when the pointer will be the same always) use the same variable (in this case counter)

CSS Sprite code works in Chrome and IE but not in Firefox?

I wrote simple animation using CSS and HTML using sprites.
It works successful in chrome and IE but not firefox.
<style type="text/css">
#sprite {
width: 96px;
height: 117px;
background: url(../../images/sprite_animation_frames.png) 0px 0px;
}
</style>
</head>
<body onload="main();">
<p align="center"><h1>The Running Man</h1></p>
<script>
var position = [
[0, 0],[-100, 0],[-200, 0],[-300, 0],[-400, 0],[-500, 0],
[0,-120],[-100,-120],[-200,-120],[-300,-120],[-400,-120],[-500,-120],
[0,-240],[-100,-240],[-200,-240],[-300,-240],[-400,-240],[-500,-240],
[0,-360],[-100,-360],[-200,-360],[-300,-360],[-400,-360],[-500,-360],
[0,-480],[-100,-480],[-200,-480],[-300,-480],[-400,-480],[-500,-480]
];
var pos;
function main(){
var img = document.createElement('img')
img.id = 'sprite';
document.body.appendChild(img);
setInterval(function () {
anim(img);
}, 50);
}
var i = 0;
function anim(el) {
if (i < 30)
i++;
else
i = 0;
var x = position[i][0];
var y = position[i][1];
el.style.backgroundPositionX = x + 'px ';
el.style.backgroundPositionY = y + 'px ';
}
</script>
what could be the problem ?
Firefox does not support individual backgroundPositionX/Y properties, and IE may be complaining about the extra space. Try:
el.style.backgroundPosition = x+"px "+y+"px";
Able to solve the problem.
Just replaced div tag instead of img and it worked.
Don't know the issue.

Progress bar not working in html file

I am creating a progrees bar is it working fine in jsfiddle demo but when i use in html file it is not working here is my code
i am writing same code as given in jsfiddle but it is not working
<html>
<head>
<style>
.ui-progressbar.beginning .ui-progressbar-value { background: red; }
.ui-progressbar.middle .ui-progressbar-value { background: yellow; }
.ui-progressbar.end .ui-progressbar-value { background: green; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<script>
var $progressbar = $("div").progressbar();
function updateProgressbar(current, target) {
var value = parseInt(current / target * 100);
$progressbar
.progressbar("value", value)
.removeClass("beginning middle end")
.addClass(value < 40 ? "beginning" : value < 80 ? "middle" : "end");
}
var total = 255;
var working = 0;
function update() {
working++;
updateProgressbar(working, total);
if (working < total) setTimeout(update, 10);
}
var $progressbar = $("div").progressbar();
function updateProgressbar(current, target) {
var value = parseInt(current / target * 100);
$progressbar
.progressbar("value", value)
.removeClass("beginning middle end")
.addClass(value < 40 ? "beginning" : value < 80 ? "middle" : "end");
}
var total = 255;
var working = 0;
function update() {
working++;
updateProgressbar(working, total);
if (working < total) setTimeout(update, 10);
}
</script>
</head>
<body onload="update()">
<div>
</div></body></html>
and here is js fiddle link working
http://jsfiddle.net/ZQrnC/305/
Look in the left sidebar of jsfiddle below "External Resources". You are embedding the jQuery UI css and js for your progressbar() there, but your html file jQuery UI is missing.
Add the following after your jquery-1.9.1.js-script-tag:
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
There are three reasons why it does not work:
As robbi5 stated you don't import the jquery ui JS and CSS files
Your var $progressbar is initialized in the header when the page is not already loaded and so no div can be found. In other words $progressbar points on nothing
Your progress bar has an height of zero making it invisble, you should wrap him a container div with a fixed height
Also your code contains duplicate part but it may due to a wrong copy/paste.
Here is an updated working version of your page with the corrected points. I checked rapidly only on chrome and firefox and it works.
<html>
<head>
<style>
.ui-progressbar.beginning .ui-progressbar-value { background: red; }
.ui-progressbar.middle .ui-progressbar-value { background: yellow; }
.ui-progressbar.end .ui-progressbar-value { background: green; }
</style>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script src=" http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
</head>
<script>
var $progressbar;
function updateProgressbar(current, target) {
var value = parseInt(current / target * 100);
$progressbar.progressbar("value", value).removeClass("beginning middle end")
.addClass(value < 40 ? "beginning" : value < 80 ? "middle" : "end");
}
var total = 255;
var working = 0;
function update() {
$progressbar = $("#pbholder").progressbar();
working++;
updateProgressbar(working, total);
if (working < total) setTimeout(update, 10);
}
</script>
</head>
<body onload="update()">
<div id="container" style="height:50px">
<div id="pbholder">
</div>
</div>
</body></html>

How to move/slide an image from left to right

I want to slide or move a image from left to right something like in
http://rajeevkumarsingh.wix.com/pramtechnology
The read pentagonal box that moves Ok!
I tried a bit but failed to do so.
I used the code as below:
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'absolute';
imgObj.style.top = '240px';
imgObj.style.left = '-300px';
imgObj.style.visibility='hidden';
moveRight();
}
function moveRight(){
if (parseInt(imgObj.style.left)<=10)
{
imgObj.style.left = parseInt(imgObj.style.left) + 5 + 'px';
imgObj.style.visibility='visible';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
//stopanimate = setTimeout(moveRight,20);
}
else
stop();
f();
}
function stop(){
clearTimeout(animate);
}
window.onload =init;
//-->
</script>
<img id="myImage" src="xyz.gif" style="margin-left:170px;" />
There some kind of resolution problem with Firefox and IE as well. How to solve them. Also I am not able to move the things so clearly. Is this possible or not? I want it to be with JavaScript and not Flash.
var animate, left=0, imgObj=null;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'absolute';
imgObj.style.top = '240px';
imgObj.style.left = '-300px';
imgObj.style.visibility='hidden';
moveRight();
}
function moveRight(){
left = parseInt(imgObj.style.left, 10);
if (10 >= left) {
imgObj.style.left = (left + 5) + 'px';
imgObj.style.visibility='visible';
animate = setTimeout(function(){moveRight();},20); // call moveRight in 20msec
//stopanimate = setTimeout(moveRight,20);
} else {
stop();
}
//f();
}
function stop(){
clearTimeout(animate);
}
window.onload = function() {init();};
Here is an example of moving an image to the right as well as fading in from a .js file instead of your index page directly:
----------My index.html page----------
<!DOCTYPE html>
<html>
<body>
<script src="myJava.js"></script>
<script language="javascript" type="text/javascript">
//In pixels
var amountToMoveTotal = 1000;
var amountToMovePerStep = 10;
//In milliseconds
var timeToWaitBeforeNextIncrement = 20;
var amountToFadeTotal = 1.0;
var amountToFadePerStep = 0.01;
</script>
<p>This one moves right on hover</p>
<img onmouseover="moveRight(this, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement)" src="http://www.w3schools.com/jsref/smiley.gif" style="left:0px;top:50px;position:absolute;opacity:1.0;">
<br><br>
<p>This one fades in on hover</p>
<img onmouseover="fadeIn(this, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement)" src="http://www.w3schools.com/jsref/smiley.gif" style="left:0px;top:150px;position:absolute;opacity:0.1;">
</body>
</html>
----------My myJava.js code----------
var animate;
var original = null;
function moveRight(imgObj, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement)
{
//Copy original image location
if (original === null){
original = parseInt(imgObj.style.left);
}
//Check if the image has moved the distance requested
//If the image has not moved requested distance continue moving.
if (parseInt(imgObj.style.left) < amountToMoveTotal) {
imgObj.style.left = (parseInt(imgObj.style.left) + amountToMovePerStep) + 'px';
animate = setTimeout(function(){moveRight(imgObj, amountToMoveTotal, amountToMovePerStep, timeToWaitBeforeNextIncrement);},timeToWaitBeforeNextIncrement);
}else {
imgObj.style.left = original;
original = null;
clearTimeout(animate);
}
}
function fadeIn(imgObj, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement)
{
//Copy original opacity
if (original === null){
original = parseFloat(imgObj.style.opacity);
}
//Check if the image has faded the amount requested
//If the image has not faded requested amount continue fading.
if (parseFloat(imgObj.style.opacity) < amountToFadeTotal) {
imgObj.style.opacity = (parseFloat(imgObj.style.opacity) + amountToFadePerStep);
animate = setTimeout(function(){fadeIn(imgObj, amountToFadeTotal, amountToFadePerStep, timeToWaitBeforeNextIncrement);},timeToWaitBeforeNextIncrement);
}else {
imgObj.style.opacity = original;
original = null;
clearTimeout(animate);
}
}
Use the jQuery library, is really easy to do what you need
http://api.jquery.com/animate/
Follow sample code of page : http://api.jquery.com/stop/
<!DOCTYPE html>
<html>
<head>
<style>div {
position: absolute;
background-color: #abc;
left: 0px;
top:30px;
width: 60px;
height: 60px;
margin: 5px;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button id="go">Go</button>
<button id="stop">STOP!</button>
<button id="back">Back</button>
<div class="block"></div>
<script>
/* Start animation */
$("#go").click(function(){
$(".block").animate({left: '+=100px'}, 2000);
});
/* Stop animation when button is clicked */
$("#stop").click(function(){
$(".block").stop();
});
/* Start animation in the opposite direction */
$("#back").click(function(){
$(".block").animate({left: '-=100px'}, 2000);
});
</script>
</body>
</html>

Javascript - Move an image to the right

This is a function thats supposed to move an image slowly to the right, it isnt working... what did i mess up?
<script type="text/javascript">
var userWidth = window.screen.width;
function moveRight(id, speed) {
var pp = document.getElementById(id);
var right = parseInt(pp.style.left);
var tim = setTimeout("moveRight(id, speed)",50);
right = right+speed; // move
if (right > window.screen.height / 2)
{
right=0;
pp.style.left = right+"px";
}
}
</script>
Looks like id and speed aren't getting passed into moveRight(). When they're in the string as you have them they won't get evaluated. Have a look at this, it seems to do the trick. I stripped it down a little.
<div id="test" style="width: 50px; height: 50px; left: 0px; background-color: #000; position: absolute;"> </div>
<script type="text/javascript">
function moveRight(id, speed) {
var pp = document.getElementById(id);
var right = parseInt(pp.style.left) || 0;
right += speed; // move
pp.style.left = right + "px";
var move = setTimeout(function() {
moveRight(id, speed);
}, 50);
}
moveRight('test', 1);
</script>
A jsfiddle to play with. You can tweak it to your liking.

Categories

Resources