Issues with hover functionality in Javascript, CSS, and HTML

Seeking assistance with my JavaScript, HTML, and CSS development, I ran into an issue while trying to create a hovering function for my webpage. Despite my efforts, the links are not displaying anything when hovered over, and the divs meant for specific hovering textboxes appear on the page at all times.

In an attempt to solve this, I have included CSS code for generic styling that should apply to different hover divs. However, I suspect there may be errors. Additionally, I've written JavaScript code for the hovering function and created divs for various hover textboxes. Unfortunately, these divs show up even when not being hovered over. Do I need additional if statements to ensure they only display during hovering? Lastly, I seek guidance on removing the blue formatting from the links, though it's a minor concern for now.

Let's start with the CSS code. Can anyone spot the potential mistake I made in writing this generic style?

div#trigger {
    display: none;
    position: absolute;
    width: 280px;
    padding: 10px;
    background: #eeeeee;
    color: #000000;
    border: 1px solid #1a1a1a;
    font-size: 90%;
  }

Next comes the JS code. Any feedback on possible errors here?

<!-- JavaScript for Hovering -->
<script>
  $(".trigger").hover(function(e) {
      var elemToShow = $(this).data("target");
      $("#" + elemToShow).show();
  }, function() {
      var elemToShow = $(this).data("target");
      $("#" + elemToShow).show();
  }).mousemove(function(e) {
      var elemToShow = $(this).data("target");
      $("#" + elemToShow).css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
  });
</script>

Finally, how can I prevent the specific hover textboxes' divs from showing when hovering is not active?

<!-- Purpose: Hover Popup -->
  <div class="trigger" target "purpose">
    <h3>Purpose</h3>
    <p>
      Test
    </p>
  </div>

   <!-- Scope: Hover Popup -->
  <div class="trigger" target "scope">
    <h3>Scope</h3>
    <p>
      dfsdf
    </p>
  </div>

Here are the links triggering the hover effect:

<a class="trigger" data-target="purpose"> Purpose:</a> Why do we want to innovate?

<a class="trigger" data-target="scope"> Scope:</a> Who are we innovating for?

Your insights and advice are greatly appreciated.

Daniel

Answer №1

take a look at this https://codepen.io/xyz123/pen/qNOPVQb/

 $(".toggle").mouseover(function(e) {        
      var targetElement = $(this).attr("data-target");          
      $("#" + targetElement).show();
  }, function() {
      var targetElement = $(this).attr("data-target");
      $("#" + targetElement).hide();
  }).mousemove(function(e) {
      var targetElement = $(this).data("target");
      //$("#" + targetElement).css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
  });

Answer №2

The CSS code contains div#trigger referenced as an ID, while the JS and HTML refer to trigger as a class with .trigger. This discrepancy could be causing the issue:

Textboxes that should only appear when hovering are appearing on the page even without hovering.

To address this problem, consider updating div#trigger in your CSS to div.trigger.

Answer №3

Issues that have arisen in your code

In this section, you are attempting to display an element by referencing its id from the data attribute of the <a> tag

 $("#" + elemToShow).show(); 

However, there are no id attributes present in your DOM, causing your div not to be displayed

 <div class="trigger" target "purpose"> // The missing ID here is preventing this div from being visible
    <h3>Purpose</h3>
    <p>
      Test
    </p>
  </div>

   <!-- Scope: Hover Popup -->
  <div class="trigger" target "scope">// The missing ID here is preventing this div from being visible
    <h3>Scope</h3>
    <p>
      dfsdf
    </p>
  </div> 

If you wish to position your div next to the pointer, you must obtain the pointer's coordinates and apply them as styles to your div

 var left  = e.clientX  + "px";
         var top  = e.clientY  + "px";
      $("#" + elemToShow).show().css({position:'absolute',top:top,left:left}).show();

You can view the working example in this fiddle https://jsfiddle.net/pps1sd32/2/

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

Tips for positioning a label at the top of a table row in an asp.net C# application

I am facing an alignment issue in my asp.net page with a table that contains a label and a textbox. Despite trying various methods, the label consistently displays at the bottom of the row. How can I ensure that the label is aligned to either the center or ...

How to create a dropdown menu in React js with an array of items

Can we structure the array without splitting it into two parts and iterating over them? arrayList=[Jeans, Jackets, Pants, Fragrance, Sunglasses, Health Products] <div className='Flexbox'> //arrayList1.map](//arrayList1.map)(x=>return(< ...

Setting a background-image using jQuery in Codeigniter can be done by following these steps

Currently, I am developing a project in Codeigniter. In my jQuery file, I have included code to set the background image of the body element: $('body').css('background-image','url(<?php echo base_url("assets/images/bg2.png");?& ...

What is the best way to set up a session using jQuery?

I've been troubleshooting my code and I can't seem to figure out why the jquery.session.js file isn't working. Can someone help me find a solution? $.session.set('rmng_time', remaining_seconds); alert("j session "+$.sessi ...

Ways to adjust the size of the parent element based on the height of a specific element

I am faced with a situation where I need to identify all elements belonging to a specific class and adjust the padding-bottom of their parent div based on the height of the matched element. For example, consider the following structure: <div class=&ap ...

Embed the div within images of varying widths

I need help positioning a div in the bottom right corner of all images, regardless of their width. The issue I am facing is that when an image takes up 100% width, the div ends up in the center. How can I ensure the div stays in the lower right corner eve ...

Transfer responsibilities of events to the canvas and then fetch the Element in the handler

Currently, I am utilizing the Raphaël library to create a network graph, where nodes are depicted as circles. Users have the ability to dynamically add nodes by clicking on the canvas. When a new node is added, an Element object is pushed into both a Set ...

In AngularJS, modifying the value of a copied variable will result in the corresponding change in the value of the main

I'm facing a peculiar issue. I have an array of objects and I used angular.forEach to update the price key value of each object. However, when I make changes in each object, it also affects the main array object. Take a look at the code snippet below ...

Tips for fixing an error encountered when running a react native project for the first time

I am encountering some errors while attempting to run this project for the first time and I am unable to resolve them. Below is the content of the package.json file: { "scripts": { "start": "expo start", "andro ...

How can you make sure that mouse events pass through the KineticJS stage?

Is it possible to have a PanoJS3 component covering the entire screen with a KineticJS stage on top, but still allow touch events to pass through the KineticJS stage to what lies beneath? I want shapes on the stage or layer to receive the touch events, wh ...

Opening a new window with Node-Webkit's start function

My application built on node-webkit has a control window and a separate presentation window. The control window collects data and triggers the opening of the presentation window using the window.open function. Once the presentation window is open, it can ...

Retrieving Ajax Data Using C#

I am struggling to send data through Ajax to a C# file. Whenever I check the received data, it always comes back as null. Could there be an issue in my code? Javascript file $(".save").click(function () { var ss = "Helloo!"; $.ajax({ typ ...

The length of the scope variable generates an error

var example = $scope.newgoal.gTitle; console.log(example.length); Even running this short code test, it throws an error message: TypeError: Cannot read property 'length' of undefined I've attempted to find various solutions without succes ...

Arranging JSON data by a specific attribute using JavaScript

As someone who is new to JavaScript, I have been working on some basic exercises. In my current code, I have a JSON data stored in a String that contains information about employees. My goal is to sort this data based on the age attribute and display the o ...

Exploring the principles of object-oriented design within the context of Node

I am facing challenges with the asynchronous flow of Node.js. Let's assume we have the following class: function myClass() { var property = 'something'; var hasConnected = false; this.connect = function(params) { // Logic to conn ...

Problems arising from the implementation of CSS modules in React applications

As a beginner in React, I recently started learning how to utilize CSS modules within my React projects. However, I encountered an error that read: Failed to compile. ./src/components/Header/Header.js Module not found: Can't resolve './Header.mo ...

Converting Epoch time to date in NextJS

In my NextJS app, I have a date displayed in a div. <div>{post.createdat}</div> The date is shown in epoch time (1609553315666), indicating the number of seconds that have elapsed since 1970. I'm wondering if there's a way to conver ...

Enclose Words Inside Unconventional Outline

Place text within a uniquely shaped border… I am attempting to achieve this goal in the most responsive and backward compatible way possible. I understand that compromise may be necessary. I have made progress with the help of this thread, but the svg ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

"JSON data is successfully obtained through Ajax Request but triggers an error in

After conducting a thorough search for the error, I came across some useful hints which unfortunately did not help in resolving the issue. Many of the queries raised were related to an invalid JSON response. The problem arises when making an Ajax request ...