A square containing two triangular interactive zones

My goal is to divide a square-shaped div diagonally, creating two triangles. Each triangle should respond to the hover event.

However, I have encountered a problem where if you move from one corner of the div directly to the opposite corner, the hover event doesn't re-trigger because it is applied to the entire div element rather than specific triangle areas.

I am open to any suggestions and willing to explore different approaches to solve this issue. Hopefully, there is a simpler solution out there!

The HTML

<div class="day_box">
</div>

The CSS

 html, body { margin: 0; }

.day_box, .upper_left_hover, .lower_right_hover, .full_day {
  background: url(/images/corner-sprites.png);
  border: 1px solid black;
  width: 25px;
  height: 25px;
  float: left;
  margin: 100px;
}

.upper_left_hover { background-position: 75px 0; }
.lower_right_hover { background-position: 50px 0; }
.full_day { background-position: 25px 0; }

The JS

  $(".day_box").hover(function(event){
    var offset = $(this).offset();
    var h = $(this).height() + offset.top;
    if((h - event.pageY)>(event.pageX - offset.left)) {
      console.log("Upper left");
      $(this).toggleClass("upper_left_hover");
    } else {
      console.log("Lower right");
      $(this).toggleClass("lower_right_hover");
    }
  });

The Fiddle: http://jsfiddle.net/zsay6/

Answer №1

If you want to incorporate the mousemove event into your code, here is how you can do it. By also including the mouseout event, you are able to remove both classes when leaving the square:

  $(".day_box").mousemove(function(event){
    var offset = $(this).offset();
    var h = $(this).height() + offset.top;
    if((h - event.pageY)>(event.pageX - offset.left)) {
      console.log("Upper left");
      $(this).removeClass("lower_right_hover");
      $(this).addClass("upper_left_hover");
    } else if ((h - event.pageY)<(event.pageX - offset.left)) {
      console.log("Lower right");
      $(this).removeClass("upper_left_hover");
      $(this).addClass("lower_right_hover");
    }
  }).mouseout(function(event) {
     $(this).removeClass("lower_right_hover upper_left_hover");
  });

Answer №2

Check out the updated fiddle here!

I made some adjustments to your fiddle to achieve the desired effect, without cleaning up the code much (just playing around, haha).

By using the right-triangle formula as explained here, I implemented the style you originally set in your fiddle. I also added a debugging div to display some values for better clarity.

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

JavaScript Arrays are not functioning properly within the Poo constructor

Attempting to insert data into a JavaScript Array within my constructor has resulted in this error message: TypeError: this.listeetudiant is undefined This is my constructor: function Cours(){ */the array causing trouble: */ this.listeetudiant=[]; */ ...

Controlling MVC controls dynamically using jQuery

I'm currently working on a table that contains multiple editable fields corresponding to an MVC model object. Each row has a cell with two buttons that toggle between edit and save functions when clicked. I've successfully implemented a mechanism ...

CSS Animations are effective in CodePen, but unfortunately, they do not function properly once integrated into an ASP.Net project

I created a unique design on codepen with a background animation, which functions properly there. However, when I integrate it into my ASP.Net Core project, the animation doesn't work as expected. The file references seem correct because the backgroun ...

Resposiveness of force-directed graph is lost

const container = document.getElementById("container"); const svgElement = d3.select(container).append("svg") // Get the width and height computed by CSS. let width = container.clientWidth; let height = container.clientHeight; const colorScale = d3.scale ...

Is it possible to streamline this HTML using jQuery to generate it?

I've been working on creating little speech bubbles for an upcoming website. While the code to make these divs is functional, I find it repetitive and time-consuming to write out every time I want to add a bubble. My solution is to utilize jQuery and ...

Leveraging the jQuery click function to toggle elements on a webpage by referencing the current element with the keyword "this

I've been trying to implement a click event that toggles an element unrelated to the selected item's parent or child. I want to utilize "this" because there are multiple elements with the same class where I'd like to apply the same jQuery cl ...

Numerous options available in a dropdown menu

I have a Dropdown menu that offers various functions. "Update" option redirects to a page for updating information "Export Form" option redirects to a page for exporting the form Although the current code allows these actions, I am facing an issue with ...

Chrome autocomplete behaves as if the input fields are disabled and cannot be clicked on

I am experiencing an unusual issue with autofill in Chrome. After logging in and then logging out of the app, the input fields (email, password) are auto-filled but appear to be frozen and unclickable. This problem does not occur every time; it only happe ...

Why should you use DIV comment tags in HTML code and how can you automate their implementation?

As I've been browsing through the codes of various professional websites, I couldn't help but notice how the HTML code is often neatly commented like this: <!-- END DIV Main Menu --> This type of commenting can be really beneficial, don&a ...

You cannot use res.json before res.redirect in Express.js

Hey there, currently I'm utilizing the express module in Node JS res.json({ auth: true, token: token, message: "success" }); res.redirect('/'); I need to send some JSON data first and then redirect. However, I encountered this err ...

Comparing the $viewValue in AngularJS with the ng-model attribute or an object parameter

I am working on a dynamic form that uses ng-min/ng-max for validation. The ng-max and ng-min are connected to object parameters modelParam.maxvalue and modelParam.minvalue. I need to show an alert or error message if the value entered in the form field goe ...

Update the value of the index() function using jQuery

Here is the HTML markup I am working with: <ul> <li id="step1">Item1<a id="button1">Move down</a></li> <li id="step2">Item2<a id="butto2">Move down</a></li> <li id="step3">Item3<a id="bu ...

Tips for creating a fixed sidebar menu that is aligned to the right side of the page

I've been working on this for quite some time now and I'm trying to figure out how to keep a side menu in place, while having it float on the right side. Every time I try using the fixed element, it ends up moving my sidebar from right to left. A ...

What sets apart `Object.merge(...)` from `Object.append(...)` in MooTools?

This question may seem simple at first glance, but upon further inspection, the MooTools documentation for the 'append' and 'merge' methods appears to be identical. Here is the code snippet provided in the documentation: var firstObj ...

Does Three.js lighting adjust according to the bundler used?

Today, I decided to streamline my portfolio project by transitioning it from standard HTML to the Vite bundler for easier dependency management. I simply copied and pasted the existing code, making adjustments to the imports since I had been using relative ...

How to display an element using an if statement in Next.js

I am attempting to incorporate a parameter into a nextJS component that will only display if a certain condition is met. At the moment, my code looks like this: return ( <div role="main" aria-label={this.props.title} classN ...

What is causing the error "unable to access property 'map' of undefined" in my code?

Currently working on React + Redux and trying to implement a likes counter. However, encountering an error 'cannot read property 'map' of undefined'. Here is the code snippet for my Reducer: const initialState = { comments: [], ...

Unable to utilize the .keyCode method within a query selector

Trying to utilize .keyCode in JavaScript to identify a pressed key, but the console consistently displays null after each key press. Below is the relevant CSS code: <audio data-key="65" src="sounds\crash.mp3"></audio> ...

Exploring the Functionality of Bootstrap 5 Collapse Component with VueJS 2

I am attempting to implement the Bootstrap 5 "collapse" component on a button in my VueJS2 project, but I am uncertain about how to integrate it. Within my single file component, the structure is as follows: <template> section: ...

Issues with Recursive Ajax Functionality in Internet Explorer 11

Trying to perform consecutive ajax GET calls using the $.ajax jQuery method in order to handle a large JSON data size of around 2MB. The process runs smoothly in Chrome, but encounters issues in IE11. In IE11, it consistently falls into the fail method dur ...