JavaScript - События мыши

Здравствуйте, будущие программисты! Сегодня мы окунемся в fascинирующий мир событий мыши в JavaScript. Как ваш доброжелательный соседский учитель компьютера, я рад помочь вам в этом путешествии. Поверьте мне, к концу этого урока вы будете обрабатывать события мыши как профи!

JavaScript - Mouse Events

Common Mouse Events

Before we jump into the code, let's take a look at some of the most common mouse events in JavaScript. Think of these as different ways your computer understands how you're interacting with your mouse:

Event Description
click Occurs when the mouse clicks on an element
dblclick Occurs when the mouse double-clicks on an element
mousedown Occurs when a mouse button is pressed down on an element
mouseup Occurs when a mouse button is released over an element
mousemove Occurs when the mouse pointer moves while it's over an element
wheel Occurs when the mouse wheel rolls up or down over an element

Now, let's explore each of these events with some hands-on examples!

Example: Click Event

Let's start with the most basic and commonly used mouse event: the click event.

<button id="myButton">Click me!</button>

<script>
let button = document.getElementById('myButton');

button.addEventListener('click', function() {
alert('Button clicked!');
});
</script>

In this example, we're telling JavaScript to listen for a click on our button. When it hears that click (like a dog hearing a whistle), it springs into action and shows an alert.

Here's what's happening step by step:

  1. We get our button using document.getElementById('myButton').
  2. We add an event listener to the button using addEventListener.
  3. We tell it to listen for a 'click' event.
  4. When a click happens, it runs the function we provided, which shows an alert.

Try it out! It's like magic, but it's actually just JavaScript doing its thing.

Example: Double Click Event

Now, let's up the ante with a double click event. It's like a click, but twice as nice!

<p id="myParagraph">Double click me to change my color!</p>

<script>
let paragraph = document.getElementById('myParagraph');

paragraph.addEventListener('dblclick', function() {
this.style.color = getRandomColor();
});

function getRandomColor() {
let letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>

In this fun little example, double-clicking the paragraph changes its color to a random color. It's like a chameleon, but cooler because you're in control!

The getRandomColor function is our little color wizard. It generates a random color each time it's called. Don't worry too much about its internals for now - just know that it gives us a random color.

Example: Mouse Down and Mouse Up Events

Now, let's look at mousedown and mouseup events. These are like the yin and yang of mouse events.

<div id="myBox" style="width: 100px; height: 100px; background-color: blue;"></div>

<script>
let box = document.getElementById('myBox');

box.addEventListener('mousedown', function() {
this.style.backgroundColor = 'red';
});

box.addEventListener('mouseup', function() {
this.style.backgroundColor = 'blue';
});
</script>

In this example, our box turns red when you press the mouse button down on it, and turns blue again when you release the button. It's like one of those stress-relief toys, but digital!

Example: Mouse Move Event

The mousemove event is triggered whenever the mouse moves over an element. It's like tracking a mouse in a maze, but less cheesy.

<div id="mouseTracker" style="width: 300px; height: 200px; border: 1px solid black;">
<p>Move your mouse in here!</p>
<p id="coordinates"></p>
</div>

<script>
let tracker = document.getElementById('mouseTracker');
let coordDisplay = document.getElementById('coordinates');

tracker.addEventListener('mousemove', function(event) {
let x = event.clientX - tracker.offsetLeft;
let y = event.clientY - tracker.offsetTop;
coordDisplay.textContent = `X: ${x}, Y: ${y}`;
});
</script>

This example creates a little mouse tracking area. As you move your mouse inside the box, it displays the coordinates. It's like you're the captain of a tiny mouse ship, navigating through a sea of pixels!

Example: Wheel Event

Last but not least, let's look at the wheel event. This event is triggered when you use the mouse wheel.

<div id="wheelDemo" style="width: 200px; height: 200px; background-color: yellow; overflow: auto;">
<p style="height: 1000px;">Scroll me using the mouse wheel!</p>
</div>

<script>
let wheelArea = document.getElementById('wheelDemo');

wheelArea.addEventListener('wheel', function(event) {
event.preventDefault(); // Prevent the default scroll behavior

this.scrollTop += event.deltaY;

if (this.scrollTop > 0) {
this.style.backgroundColor = `rgb(255, ${255 - this.scrollTop}, 0)`;
}
});
</script>

In this example, as you scroll the wheel, the background color changes from yellow to red. It's like a sunset, but you control it with your mouse wheel!

The event.deltaY gives us the amount of vertical scroll. We use this to both scroll the content and change the color.

And there you have it, folks! We've journeyed through the land of JavaScript mouse events. Remember, practice makes perfect, so don't be afraid to experiment with these events. Before you know it, you'll be creating interactive web experiences that will make your users say "Wow, how did they do that?"

Happy coding, and may your mouse always click true!

Credits: Image by storyset