Entrance Chat Gallery Guilds Search Everyone Wiki Login Register

Welcome, Guest. Please login or register. - Thinking of joining the forum??
February 21, 2026 - @266.78 (what is this?)
Activity rating: Four Stars Posts & Arts: 64/1k.beats Unread Topics | Unread Replies | My Stuff | Random Topic | Recent Posts Start New Topic  Submit Art
News: :sleep: These are fast times on the World Wide Web~ Guild Events: There are no events!

+  MelonLand Forum
|-+  World Wild Web
| |-+  ✁ ∙ Web Crafting
| | |-+  ☔︎ ∙ I need Help!
| | | |-+  Help a complete beginner with some javascript?


« previous next »
Pages: [1] Print
Author Topic: Help a complete beginner with some javascript?  (Read 122 times)
John
Casual Poster ⚓︎
*
View Profile WWW


⛺︎ My Room

Guild Memberships:
Artifacts:
Joined 2026!
« on: February 11, 2026 @612.20 »

(I did read the How to use this section!-Post and thought, oh great, that's probably it, but I didn't manage to get the Python local webserver solution running, though I just uploaded it to neocities after and that should work too, shouldn't it? ... oh, hey I just understood what "Always do Inspect, and check the Inspector Console" means, and the console actually shows an error, but I don't understand what the error means.)

Hello, does anyone have the patience to help an absolutely clueless beginner, if you can even call me that, to get some java script running?

So, I found this cursor effect which I'd like to use and modify later.  (Basically, the end-result I'm looking for is a gif smoothly following the cursor with a slight delay.) I put it together like this:

Code
<!DOCTYPE html>
<html>

<head>

    <style>
body { 
    overflow:hidden; position:absolute; height:100%; width:100%; background:#efefef; }

#cube {
  height:18px;
  width:18px;
  margin-top:-9px;
  margin-left:-9px;
  background:red;
  position:absolute;
  top:50%;
  left:50%;   
}

.circleBase {
    border-radius: 50%;
}

.roundCursor {
    width: 20px;
    height: 20px;
    background: red;
    border: 0px solid #000;
}
    </style>

    <script>
  $(document).ready(function () {

  $("body").mousemove(function (e) {
    mouseMoveHandler(e);
  });
  var currentMousePos = { x: -1, y: -1 };
  function mouseMoveHandler(event) {
    currentMousePos.x = event.pageX;
    currentMousePos.y = event.pageY;
  }

  mouseMover = setInterval(positionUpdate, 15);

  function positionUpdate() {

    var x_cursor = currentMousePos.x;
    var y_cursor = currentMousePos.y;
    var position = $("#cube").offset();
    var x_box = position.left;
    var y_box = position.top;

    $("#cube").animate({
      left: x_box+0.1*(x_cursor-x_box),
      top: y_box+0.1*(y_cursor-y_box) 
    }, 1, "linear"); 
  }
});
    </script>

</head>


<body>
    <div id="container">

        <div class="circleBase roundCursor" id="cube"></div>

    </div>
</body>


</html>

Here it is uploaded to neocities: https://johnshomepage.neocities.org/castle/jstest and the red dot doesn't follow the cursor. (EDIT: I have by now downloaded jQuery and added it, but probably did something wrong, so there's a new error you'll find on the linked site.)

The inspector console says:

  "Uncaught ReferenceError: $ is not defined
    <anonymous> https://johnshomepage.neocities.org/castle/jstest:34"

It would probably be really obvious what I did wrong, if I knew anything about Javascript ... could anyone point me in the right direction?
« Last Edit: February 11, 2026 @653.39 by John » Logged

Kind regards,
bodypoetic
Casual Poster ⚓︎
*
View Profile WWWArt


for thine is the kingdom of wire and bone
⛺︎ My Room
Itch.io: My Games
RSS: RSS

Guild Memberships:
Artifacts:
Thank you for sending me a postcard!Joined 2025!
« Reply #1 on: February 11, 2026 @625.79 »

Hey! With the disclaimer that I am also reeeeelatively new to JavaScript and may have this wrong:

Uncaught ReferenceError basically means that the code doesn't know what you're referring to. In this case, that's the dollar sign.

Using '$' like that is a jQuery thing. jQuery is a library designed to make JavaScript simpler, although I gather there's some debate on how necessary it actually is. In your case, because you don't have jQuery implemented, the code doesn't know what to do. You can either add in jQuery (w3schools has a tutorial on it here) or convert the code into regular JavaScript. Regrettably I don't know what that would look like off the top of my head, but I'm sure there's tutorials on it out there somewhere. (Also I'd be surprised if there wasn't somebody else on the forum able to help you with that.)

Hopefully this is a helpful lead!
Logged

Quote
The prince chose to sleep on, and the princess chose to wake up. At the top of that tall tower, the princess bid farewell to the prince. No—she wasn’t the princess any longer. She quit being a “person (thing) ruled by someone”. The victory bells rang, but there was no “tower (rule)” beyond them now. She’d learned where freedom lay. [...]

The world (the stage) is free and wide.

John
Casual Poster ⚓︎
*
View Profile WWW


⛺︎ My Room

Guild Memberships:
Artifacts:
Joined 2026!
« Reply #2 on: February 11, 2026 @643.40 »

Thank you! So downloading jQuery and putting it in the same directory and adding the source reference to the script tag should theoretically solve the problem. It didn't, but at least now I've got a different (and more sophisticated?) error message. : D Haven't really tried to fix it yet, got to go have coffee with the family, and will try again after.
Logged

Kind regards,
John
Casual Poster ⚓︎
*
View Profile WWW


⛺︎ My Room

Guild Memberships:
Artifacts:
Joined 2026!
« Reply #3 on: February 11, 2026 @715.12 »

I fixed the issue with the jquery file, I think, and now it still doesn't work and there's a very different and seemingly unrelated error message? To me it looks like it's trying to get the fav-icon, but can't find it? But I didn't even put that in the css for that page? Sorry for my all-around incompetence.
Logged

Kind regards,
ヤーナム
Casual Poster
*
View ProfileArt


hanging out on AIM
⛺︎ My Room

Guild Memberships:
Artifacts:
Joined 2023!
« Reply #4 on: February 11, 2026 @775.79 »

You're very close! The problem is that you're combining two separate `<script>` tags. You need one for including jQuery and one for your inline script, like this:

Code: javascript
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>

<script type="text/javascript">
  $(document).ready(function () {
    $("body").mousemove(function (e) {
      mouseMoveHandler(e);
    });
    var currentMousePos = { x: -1, y: -1 };
    function mouseMoveHandler(event) {
      currentMousePos.x = event.pageX;
      currentMousePos.y = event.pageY;
    }

    mouseMover = setInterval(positionUpdate, 15);

    function positionUpdate() {

      var x_cursor = currentMousePos.x;
      var y_cursor = currentMousePos.y;
      var position = $("#cube").offset();
      var x_box = position.left;
      var y_box = position.top;

      $("#cube").animate({
        left: x_box+0.1*(x_cursor-x_box),
        top: y_box+0.1*(y_cursor-y_box) 
      }, 1, "linear"); 
    }
  });
</script>
Logged
Dan Q
Sr. Member ⚓︎
****
View Profile WWWArt


I have no idea what I am doing
⛺︎ My Room
RSS: RSS

Guild Memberships:
« Reply #5 on: February 11, 2026 @839.17 »

Okay, so I started looking at this from a perspective of "why are we loading 77kb of jQuery when we only need about two lines of it?". Then I realised there were a lot more efficiencies and performance improvements that could be made. Then I basically re-wrote the thing!

Here's how I'd do it. I've added a ton of comments so it can be used as a learning example. I've put it into an interactive Codepen if you'd like, or the source code is all below:


Code
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252">
<style>
body { 
  overflow:hidden;
  position:absolute;
  height:100%;
  width:100%;
  background:#efefef;
}

/* Here's the styles for your "cursor chaser", the: <div id="cursor-chaser"></div> */
#cursor-chaser {
  /* This bit positions it right in the centre of the page to begin with: */
  position:absolute;
  top: 50%;
  left: 50%;

  /* This bit affects what it looks like: */
  background:red;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  border: 0px solid #000;

  /* These should be MINUS exactly half the width and heigh, to "offset" the position: */
  margin-top: -10px;
  margin-left: -10px;

  /* This affects the animation speed. 0.1s means it'll take a tenth of a second to "catch up" to the mouse pointer: */
  transition: left 0.1s, top 0.1s;
}
</style>

<title> | https://johnshomepage.neocities.org/</title>
</head>
<body>
  <div id="container">
    <div id="cursor-chaser"></div>
  </div>

  <script>
    /* This script goes at the BOTTOM of the page. This means we don't need to check if the page has loaded before we
     * can access the <div id="cursor-chaser"></div>, because we know it was already drawn (up 👆 there somewhere)!
     */

    // Find the <div id="cursor-chaser"></div> (by its id) and put it in a variable, cursorChaser
    const cursorChaser = document.getElementById('cursor-chaser');

    // Store a variable called currentMousePos so that currentMousePos.x and currentMousePos.y start at -1 (we'll change them later!)
    let currentMousePos = { x: -1, y: -1 };

    // Every time we move the mouse over the page, run this code:
    document.addEventListener('mousemove', e => {
      // Set currentMousePos.x and currentMousePos.y to the current position of our cursor (so the chaser knows where to chase!)
      currentMousePos.x = event.pageX;
      currentMousePos.y = event.pageY;
    });

    // Start a repeating timer to move the "chaser". We're going to run positionUpdate every 15 hundredths of a second.
    // (you can make it more or less frequent; the lower this number, the smoother corners will be but the worse performance will be)
    setInterval(positionUpdate, 15);

    // Here's the function that runs every 15 hundredths of a second:
    function positionUpdate() {
      // First, check if currentMousePos.x or currentMousePos.y are still -1; if so, we've not seen a cursor move yet, so drop out!
      if(currentMousePos.x < 0 || currentMousePos.y < 0) return;

      // Get the current X and Y coordinates of the "chaser". This is a bit gnarly, sorry!
      const cursorChaserPosition = cursorChaser.getBoundingClientRect();
      const x_box = cursorChaserPosition.left + window.pageXOffset - document.documentElement.clientLeft;
      const y_box = cursorChaserPosition.top + window.pageXOffset - document.documentElement.clientTop;

      // Now, CHANGE the left and right coordinates of the chaser so they're the same as that of the mouse cursor when it last moved.
      // The animation is handled by the CSS "transition:" directive! This gives best performance and requires little JS.
      // The "-10" is the same as the margin-top and margin-left; it makes sure that the circle FINISHES right on the centre of the cursor.
      cursorChaser.style.left = `${(currentMousePos.x - 10)}px`;
      cursorChaser.style.top = `${(currentMousePos.y - 10)}px`;
    }
  </script>
</body>
</html>

Specific changes I made were:

  • Removed jQuery and re-wrote using vanilla JS (faster, cleaner, simpler).
  • Switched from doing the animation in JS to doing the animation in CSS (easier to tweak, faster).
  • Instead of using an ID and two classes to refer to the chaser, used just its ID in both the JS and CSS (less code, simpler).
  • Moved the <script> to the bottom (removes the need for checking if the body has loaded yet).
  • Switched "var" for "const" or "let". "var" provides a lot of ways for beginners to shoot themselves in the foot with JS! "var" means "this is a variable, give MY WHOLE PAGE access to it", which means that if you name something the same way twice, your code does Weird Stuff. "let" is basically the same... but the variable is scoped so it only works within the block of code it's in. "const" is like let, but you can't change a const (you can ignore that one and use "let" everywhere if you like!).
  • Removed un-needed (I hope!?) classes from the <html> tag.
  • Added a ton of comments (easier to understand!).

Have a play with some of the variables; give some of the numbers a tweak until you love the way the animation feels.

If I were to change only one additional thing, it'd be to make the chaser invisible (CSS - display: none;) to begin with, and then make it visible (JS - cursorChaser.style.display = 'block';) on the first run of positionUpdate() that DOESN'T return early because the cursor hasn't moved. That way, the blob doesn't appear unless you actually move your mouse over the page (so it doesn't appear to keyboard-only users, for example).

(If I were to change a second additional thing, I've swap out setInterval for requestAnimationFrame, which would probably make the animation smoother and would make it easier for web browsers to optimise for it... but I just wanted to throw something "cleaner, and learn-from-able" together while I was in a boring bit of a meeting, so that's all you get for now! :cheesy: )
Logged


Artifact Swap: PolyamorousI met Dan Q on Melonland!Joined 2025!Lurby
John
Casual Poster ⚓︎
*
View Profile WWW


⛺︎ My Room

Guild Memberships:
Artifacts:
Joined 2026!
« Reply #6 on: February 11, 2026 @850.98 »

First: Thank you, ヤーナム! That did the trick! And sorry again for not knowing the basics!




It starts to get really laggy after a short while, but now that I got it running, I can fiddle with it ...

... is what I wanted to write, but I guess that's obsolete. :D Wow, Dan, thank you so much! I have to put the children to bed now and can't go through your reply in detail tonight, but I'll try it all tomorrow!

Logged

Kind regards,
Dan Q
Sr. Member ⚓︎
****
View Profile WWWArt


I have no idea what I am doing
⛺︎ My Room
RSS: RSS

Guild Memberships:
« Reply #7 on: February 11, 2026 @944.03 »

First: Thank you, ヤーナム! That did the trick! And sorry again for not knowing the basics!

Don't apologise for that. Nobody is born knowing JavaScript! Anybody who writes it has to learn it, and this - taking well-documented code and "playing with" it - is IMHO the best way to do so.

It starts to get really laggy after a short while, but now that I got it running, I can fiddle with it ...

Suspect my version will get less-laggy because it doesn't cascade calls to $('#cube').animate() like the jQuery one did. The big problem with that approach from a performance perspective is that it potentially doesn't cancel the previous animation before starting the next one, so you can end up with a growing or near-infinite number of animations running!

My approach, instead, changes the "position" of the chaser... and then lets CSS optimise tween the animation. CSS is almost always faster than JavaScript, because the browser gets to take all kinds of shortcuts (because it knows the end result, unlike with JavaScript code where it can never be certain that some function won't do something wonky!). So as a rule of thumb: if something can be done in JS or can be done in CSS... the CSS approach is superior, all other things being equal.

(this is literally an argument I make about twice a week at my Day Job, where they're so JavaScript-obsessed that 90% of the time they're happy to only use the <div> element and a stack of onClick/onHover/etc. events to make those <div>s act a bit like links, buttons, and the like... which then completely breaks as soon as somebody tries to use a keyboard rather than a mouse, or tries to use "open in new tab", or something: it drives me crazy!)
Logged


Artifact Swap: PolyamorousI met Dan Q on Melonland!Joined 2025!Lurby
Pages: [1] Print 
« previous next »
 

Melonking.Net © Always and ever was! SMF 2.0.19 | SMF © 2021 | Privacy Notice | ~ Send Feedback ~ Forum Guide | Rules | RSS | WAP | Mobile


MelonLand Badges and Other Melon Sites!

MelonLand Project! Visit the MelonLand Forum! Support the Forum
Visit Melonking.Net! Visit the Gif Gallery! Pixel Sea TamaNOTchi