Move the cursor over the text to reveal an image

Hello, I'm trying to replicate the same animation effect as seen on these websites: and . Specifically, when hovering over the "selected works" section, an image is displayed. I suspect it's using a JavaScript library, but I can't seem to identify which one. I've been searching for hours without success, so any assistance would be greatly appreciated!

Answer №1

Upon observation, it appears that the <a> tags on those websites react to hover actions. Achieving this effect can be accomplished through JavaScript or CSS, depending on the desired reaction.

If you aim to display an image around your cursor similar to the showcased websites, you must utilize either an event listener or a custom cursor. It is worth noting that the websites examined did not employ a custom cursor, as the regular pointer cursor remains visible.

Below is an example of how this can be achieved with JavaScript and some CSS (the image appears and follows the cursor, disappearing when the link is no longer hovered over).

HTML:

<div id="container">
  <a href="" data-src="road.png" class="hover">
    <h1>Hover here!</h1>
  </a>
</div>

Ensure that the href attribute contains the desired destination URL when clicked. If no hyperlink is needed (assuming both referenced websites have links), the element could be changed to a <div> or another suitable tag. The data-src attribute plays a crucial role by specifying which image to use in JavaScript. While alternative methods exist, utilizing datasets for passing small information between HTML and JavaScript is preferred. The naming convention isn't critical as long as it begins with "data-" (e.g., data-image or data-href).

CSS:

#container {
  position: relative;
}
.followMouse {
  z-index: -1;
  position: absolute;
}

The class followMouse will be used when displaying the image. A negative z-index places it behind other elements on the page, aligning with the examples provided. Setting its position to absolute is crucial for defining coordinates without affecting surrounding styling. Therefore, assigning a relative position to the parent element (in this case, the one with the id "container") is essential.

Now onto the implementation with JavaScript:

for (let el of document.querySelectorAll('.hover')) {
  let image = new Image();
  image.src = el.dataset.src;
  image.className = "followMouse";
  el.addEventListener('mouseover',(e)=>{
    document.getElementById('container').append(image);
    image.style.left = `${e.x - (image.width/2)}px`;
    image.style.top = `${e.y - (image.height/2)}px`;
  })
  el.addEventListener('mouseout',(e)=>{
    image.remove();
  })
}
window.addEventListener('mousemove',(e)=> {
  let image = document.querySelector('.followMouse');
  if (image) {
    image.style.left = `${e.x - (image.width/2)}px`;
    image.style.top = `${e.y - (image.height/2)}px`;
  }
})

By using document.querySelectorAll, all elements with the 'hover' class can trigger this behavior together. Accessing the data-src attribute involves referencing the element's dataset. Subsequently, an image is loaded based on this attribute linked with the class followMouse. Delaying appending ensures the image only appears upon hovering over the element. For each element with the 'hover' class, two event listeners are added: one to show the image within the container on mouseover and another to remove it onmouseout. When showing the image, adjustments to its style ensure proper alignment with the cursor at the center. Since direct access to CSS attributes such as 'left' and 'top' requires string input, template literals allow dynamic content insertion via ${insert js here}. Lastly, a window-wide event listener monitors cursor movement, dynamically updating the image position while hovering over elements triggering the interactive response.

Answer №2

<div class="portfolio">
          <a class="thecococlub" href="project/the-coco-club.html">  <div class="folio" >
                <p>001</p>
                <hr>
                <h3>THE COCO CLUB</h3>
            </div></a>
            <div class="folio" >
                <p>002</p>
                <hr>
                <h3>Tanja Kuriger Fotografie</h3>
            </div>
            <div class="folio">
                <p>003</p>
                <hr>
                <h3>Metall Schmiededesign</h3>
            </div>
            <div class="folio">
                <p>004</p>
                <hr>
                <h3>Creative & Code</h3>
            </div>

            <a href="project/maeva.html">
            <div class="folio">
                <p>005</p>
                <hr>
                <h3>Maeva</h3>
            </div></a>
            <div class="folio">
                <p>006</p>
                <hr>
                <h3>Mint Fashion</h3>
            </div>
        </div>

and below is the associated css:

.thecococlub::before{
  content: " ";
}

.thecococlub::after{
  content: " ";
  background-image: url("../img/thecococlub_500px.png");
  width: 500px;
}

Answer №3

If you want to make your cursor stand out, consider using an image as the mouse cursor instead of the default arrow. You have the option to choose between SVG, PNG, or GIF (non-animated). To trigger the change in cursor on hover, utilize the :hover pseudo-selector.

The custom mouse cursor image will appear at the bottom-right from the point where you "aim" it. Adjusting the offset in pixels can help you position the cursor image more centrally.

a:hover {
  cursor: url("https://via.placeholder.com/100.png") 50 50, auto;
}


/* for styling purpose only */
body {
  margin: 0;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
<a href="#">Hover me!</a>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Nested Angular Controller in a ng-repeat loop

I am attempting to utilize a nested controller within an ng-repeat in order to have the accordion panels on the page function in different scopes. However, I am encountering a problem where the code inside the nested controller is not being executed. I pla ...

Struggling to eliminate the padding beneath the menu items in Bootstrap?

I'm having trouble adjusting the padding inside my menu. I want to make it less chunky and large, but so far I've only been successful in removing the top padding. The bottom padding just won't budge. Here's the code that helped fix th ...

The npm install command failed due to a lack of suitable versions for pinkie-promise

I am currently attempting to perform a straightforward "npm install" from one of the repositories mentioned in a tutorial provided here Below is the content of the package.json: { "name": "react-playlist", "version": "1.0.0", "description": "A basi ...

Arrange the parallel table columns within their own individual divs to be perfectly aligned

I have a layout with two divs stacked on top of each other, each containing a table with the same number of columns. I need to ensure that the columns in both tables are the same width and aligned properly. If a column in one table expands, I want the corr ...

The error message in Express points to module.js line 550 and states that the module cannot be

I am currently in the process of setting up a basic express application using the code below: const express = require('express'); const app = express() const bodyParser = require('body-parser'); const cookieParser = require('cooki ...

Encountering a "Cannot GET" error when utilizing mongoose

Details of my router.js file: const express = require("express") const Note = require("../models/nodeModel") const router = express.Router() router.route("/notes").get((req, res) => { Note.find({ show_day: "2020-9-10" }) .then(foundNotes ...

Exploring Vue Routing with Regular Expressions

Recently, I integrated a route with a parameter in my Vue project. const routes = [ { path: "/:lang(^$|^es$|^pt$|^cn$)", name: "Home", component: Page, }, { path: "/privacy", name: "Privacy", component: Privacy, }, { ...

Step-by-step guide on eliminating the modal post-validation

Newbie in reactjs looking for help with modal validation issue. Goal: Press submit button inside modal, validate, then close the modal. Want to reuse modal for another row. Problem: I'm having trouble making the function work for a new row after ...

Ways to utilize array reduce for organizing information

Can someone please guide me on how to use the reduce array method to sort entries by date in the following data: const entries = [ {date: 'lu'}, {date: 'lu'}, {date: 'ma'}, {date: 'ma'} ] I would like the ou ...

Tips for inserting information from a JSON file into a mailto hyperlink

As a newcomer to JavaScript, I am eager to tackle the challenge presented below: Situation: In possession of a JSON file containing personal details such as name, email address, bio, etc., my task is to design a basic web page showcasing this data for ea ...

Eliminate any additional spacing or padding surrounding the text input field

Is there a way to adjust the inner padding of a text field? Currently, when entering text in an HTML text field, there is padding at the beginning and end. The numbers I am inputting have no more than 3 digits, and the current padding takes up about the wi ...

Error: The bun.js application encountered a SegmentationFault at line 188

I'm attempting to execute the following command on my current repository, which already has a registry set up in the .npmrc. bun install -y The purpose of the -y flag is to generate the yarn v1 lockfile. However, it's resulting in the followin ...

JavaScript for beginners: show a specified amount of search results and insert a loading indicator at the end

Currently, I have a website that retrieves data from my database using a PHP query. However, the issue I am facing is that there are over 300 entries in my database, resulting in an excessively long displayed page. My main question: How can I restrict ...

What is the best way to change an array of strings into a single string in JavaScript?

I am working with a JavaScript array that contains strings arranged in a specific format: arrayOfString = ['a', 'b,c', 'd,e', 'f']; My goal is to transform this array into a new format like so: myString = ["a", "b ...

How to effectively transfer a JSON object from a Python function to JavaScript using Eel, allowing you to seamlessly utilize and modify the JSON data

Let's delve into a slightly confusing question together. Have you heard of Eel? It's a Python module that lets you use functions created in Python in Javascript, and vice versa. What I want to achieve is taking a JSON object generated by a Python ...

The Vue component mistakenly saves the image to the incorrect location when the file @change event is triggered

I've encountered an issue with my image slider component. Users have the option to add an extra image to the end of the slider, but when there are multiple instances of the same slider component on a page, it always adds the image to the first compone ...

Is your $http request causing an XML parsing issue?

I'm attempting to utilize the $HTTP method from angularJS to access my restful web service. On entering my web service URL in the browser, I receive a result of APPLICATION/JSON type. {"id":20418,"content":"Hello, World!"} The URL for my web servic ...

Guide to transmitting a "token" to an "API" using "React"

As a novice developer, I am facing a challenge. When users log in to our website, a JWT is created. I need to then pass this token to the API on button click. If the backend call is successful, the API response should be displayed. If not, it should show ...

Using Angular to store checkbox values in an array

I'm currently developing a feature that involves generating checkboxes for each input based on the number of passengers. My goal is to capture and associate the value of each checkbox with the corresponding input. Ultimately, I aim to store these valu ...

Struggling with implementing jQuery AJAX in Node.js Express - any tips?

Struggling with implementing ajax in node js for the first time. I've been testing it using the console, but unable to get a response. Here's my code: <script> function getMessage() { var data = $("#messageselect").val() $.ajax({ ...