Encase a Component within a Button

In my current project using React, I've successfully implemented a feature where a ball follows the cursor with JavaScript. The ball only appears when it hovers over a button element, thanks to this CSS block:

#app button:hover + .ball {
  display: block;
}

.ball {
  display: none;
}

While this functionality is working well, I am now exploring ways to ensure that the ball remains contained within the button itself. Currently, when hovering near the edge of the button, the ball extends beyond its boundaries.

Check out the project codepen here

Answer №1

If you enclose the button and the .ball elements within a container div, you can apply the CSS property overflow:hidden to the container:

Inside the render function:

<div className="button-container">
  <button>BUTTON</button>
  <div ref={ballRef} className="ball"></div>
</div>

In the stylesheet:

.button-container {
  position: relative;
  display: inline-block;
  overflow: hidden;
}

let mouseX = 0
let mouseY = 0
let ballX = 0
let ballY = 0
let speed = 0.2

const Page = () => {
  const ballRef = React.useRef(null)
  const animate = React.useCallback(() => {
    if (ballRef && ballRef.current) {
      let distX = mouseX - ballX
      let distY = mouseY - ballY
      ballX = ballX + distX * speed
      ballY = ballY + distY * speed
      ballRef.current.style.left = ballX + "px"
      ballRef.current.style.top = ballY + "px"
    }
    requestAnimationFrame(animate)
  }, [ballRef, mouseX, mouseY, ballX, ballY])

  React.useEffect(() => {
    const onMouseMove = event => {
      mouseX = event.pageX
      mouseY = event.pageY
    }

    document.addEventListener("mousemove", onMouseMove)

    animate()

    return () => document.removeEventListener("mousemove", onMouseMove)
  }, [])  

 return (
   <> 
     <div className="button-container">
       <button>BUTTON</button>
       <div ref={ballRef} className="ball"></div>
     </div>
     <div class="divs"></div>
     <div class="divs"></div>
   </>
  );
}

ReactDOM.render(<Page/>, document.querySelector('#app'));
#app button:hover + .ball {
  display: block;
}

.button-container {
  position: relative;
  display: inline-block;
  overflow: hidden;
}

.ball {
  display: none;
}

button{
  background-color: green;
  padding: 20px;
}

.ball {
  background-color: red;
  width: 26px;
  height: 26px;
  border-radius: 50%;
  position: absolute;
  top: 0;
  left: 0;
  transform: translate(-50%, -50%);
  mix-blend-mode: screen;
  transition: transform 0.4s, border 0.4s;
  border: 2px solid transparent;
  pointer-events: none;
}

.divs{
  background-color: gray;
  padding:20px;
  margin:20px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>

<div id="app"></div>

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

Navigate through the website by transforming the arrow and clicking the link

I am struggling with transitioning my arrow from › (right) to ˇ (down) when toggled. I can't figure out where to place it. If you look at Menu 1 > Submenu 1 > Text with hyperlink I want the 'Text with Hyperlink' to be clickable on ...

Identify the descendant of the `<li>` tag

I need help creating a interactive checklist. The idea is that when you click on an item in the list, a hidden child element should become visible. <div id="list_one"> <h2>LIST TITLE</h2> <div id="line"></div> < ...

Browsing through a collection of JSON objects with a user interface

I need a way to filter and display a list of Dogs based on a search query. I initially stored the data in an array within the state, but with an increasing number of entries, I've decided to switch to JSON format for better management. However, I&apo ...

Sharing CSS styles among multiple single-page applications (SPAs) developed using the React

I am currently working on multiple micro SPAs that exist independently within an Express environment. I am facing a challenge with importing a global CSS file that is located outside of the apps, as it is not being recognized. The use of @import url(asset ...

Navigating Through Secondary Navigation with Ease

In my React project, I am developing a mega-menu styled dropdown navigation. As a functional component, I am utilizing the useState hook to manage the state and control the display of sub-navigation items. The functionality of the dropdown is operational, ...

Ways to implement Formik to output a boolean value?

Currently, I am facing an issue retrieving a value from Formik. While it works perfectly fine with a Textfield component, I am unable to fetch the value of my switcher (which is a boolean). The setup for my file and switcher looks like this: <div clas ...

Issue encountered while rendering HTML using express

I've been experimenting with a basic single-page render and it seems like I'm missing something: const express = require('express'); const app = express(); app.get('/', function(req, res){ res.render('home.html' ...

Is there a way to utilize JSON data to dynamically fill column names in a JQuery datatable?

JSON Data: { "data": [ { "name": "Garrett Winters", "designation": "Accountant", "salary": "$170,750", }, { "name": "Brielle Williamson", "designation": "Integration Specialist", "salary": "$372,000", } ] } H ...

Use an external javascript file in AngularJS if permitted

To ensure that my HTML page only loads an external JavaScript file when the variable $scope.jsallowed is set to true, I attempted the following code implementation within my AngularJS based page: <script src="assets/js/slider.min.js" data-ng-if="jsallo ...

jQuery Soundboard - Pressing a single button will automatically deactivate all other buttons

I am currently developing a unique jQuery/PHP soundboard feature where I am faced with the challenge of stopping the HTML5 Audio playback when clicking on just one button, while attached to several other buttons. Here is what I have managed to code so far: ...

Sharing dynamic scientific findings through Python publication

I'm uncertain if this inquiry aligns with the theme of this community, yet I am at a loss for where to pose it. While my background doesn't involve web programming, I have recently embarked on a web venture that incorporates various JavaScript l ...

Issues with Transition property not affecting Box-Shadow styling

Although this question may have been asked before, I am confident that I have thoroughly researched and attempted multiple solutions. I have experimented with various methods to make this box-shadow transition work, such as: Switching between hex, rgb, a ...

How can I use jQuery to set the color of every other row in a

I'm facing an issue where I want to use jQuery to set the color of alternate rows in an HTML table. However, every time I add a new row, the color of the entire table switches. Below is the JavaScript code snippet that I am utilizing: var alternate = ...

What steps can be taken to execute a function when a button remains unclicked?

$("#RunCode").click(function(){ var $this = $(this); if($this.data('clicked')) { console.log("Is clicked"); $(".documentWrite").text("Is clicked"); } else { $this.data('clicked', true); consol ...

Turn off transparency for the child element if the parent element has transparency

In my design setup, there is a container with an opacity set at 0.8. This allows the background image to subtly shine through the content area. The challenge arises when I place a client photo inside this container. The issue is that the photo's opac ...

Tips for creating CSS3 animations in Angular triggered by mouse clicks

I'm working with a span that utilizes a Bootstrap icon. My goal is to fade out and fade in the same element (span) on click, while toggling the class (icon). There's a boolean variable called showLegend which determines whether or not to animate ...

Mobile Mode Issue with Bootstrap 4 Navbar Example

Currently, I am exploring the Bootstrap material and trying to understand how to integrate their content with a jinja2 file that I am preparing for a django project. Upon attempting to copy and paste their example code (specifically this example http://get ...

Running a series of functions consecutively with JQUERY

Currently, I am facing an issue with using an ajax method .load to replace the content of a div. The library I am working with does not allow me to replace the content of a div as some functions continue to run in the background. To overcome this challeng ...

Another method to verify an input using HTML5 regex and JavaScript

When working with vanilla JavaScript to check an HTML input against a regex pattern, things can get tricky. I find myself going back to the parent element to validate the input, and while it works, it's not as elegant as I would like it to be. Here i ...

utilizing Typescript object within an array of objects

How can I optimize typing this nested array of objects? const myItem: Items[] = [{ id: 1, text: 'hello', items: [{ id: 1, text: 'world' }] }] One way to approach this is by using interfaces: interface It ...