Utilizing the "onmouseover" event to show a tooltip with JavaScript

Is there a way to create small dialogue boxes using JavaScript for user guidance when entering data into a field by hovering over them? I am new to JavaScript and not sure if my approach is correct.

Here is the code I have:

<html>
    <head>
        <style type="text/css">
            #button {
                border-radius: 50%;
                border: 1px solid black;
                padding-top: 3px;
                padding-bottom: 3px;
            }
            #info {
                margin-left: 5%;
            }
            #help_container {
                border: 0.5px solid black;
                background-color: #efefef;
                width: 20%;
            }
            #close {
                float: right;
                margin-top: 1%;
                background-color: #efefef;
                border: 0px solid #efefef;
            }
            #help_text {
                margin: 5%;
                font-family: Arial;
                font-size: 15px;
            }
        </style>
    </head>
    <body>
        <div>
            <button id="button" onmouseover="mOver(this)" onmouseout="mOut(this)">?</button>
        </div>

        <script>
            function mOver(obj) {
                obj.innerHTML = "<div id='help_container'><button id='close'>X</button><p id='help_text'>Help Text</p></div>";
            }

            function mOut(obj) {
                obj.innerHTML = "<button id='button' onmouseover='mOver(this)' onmouseout='mOut(this)'>?</button>";
            }
        </script>
    </body>
</html>


I'm experiencing issues with the function as it's not working as expected. When hovering over or away from the button tag, changes occur but not the ones I anticipated. My goal was to display a small div with help text inside, and ideally include a close button within the div that triggers a function to remove the element using onclick, but I am unsure how to achieve this.

Any suggestions on resolving the onmouseover function or implementing a way to close the div with onclick would be highly appreciated.

Thank you in advance!

Answer №1

Utilizing Bootstrap or any other JavaScript library in conjunction with jQuery can achieve the same goal effectively. It is recommended to leverage these tools for enhanced functionality.

Take a look at the code snippet provided below.

HTML

<a data-toggle="tooltip" title="add to cart">
    <i class="icon-shopping-cart"></i>
</a>

JavaScript and CSS

$('a[data-toggle="tooltip"]').tooltip({
    animated: 'fade',
    placement: 'bottom',
});
.cart {
    overflow: hidden;
    padding: 10px 3px;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet"/>

<div class="cart"> 
    <a data-toggle="tooltip" title="add to cart">
        <i class="icon-shopping-cart"> Cart</i>
    </a>
</div>

Answer №2

If you want to create a tooltip using CSS and HTML only, you can follow the code below:

CSS:

<style type="text/css">
            div#tooltip a span {display: none;}
            div#tooltip a:hover span {display: block;
               position: relative; width: 125px;
               padding: 5px; margin: 10px; z-index: 100;
               color: black; background-color:#FFFFCC; border: 1px solid #ccc;
               font: 10px Verdana, sans-serif; text-align: center;}

            div#tooltip a {
              position:relative;
            }
            div#tooltip a span {
              display:none;
            }
            div#tooltip a:hover span {
              display:block;
              position:absolute; width: 100px;
              color: black; background-color:#FFFFCC; border: 1px solid #ccc;
              font: 10px Verdana, sans-serif; text-align: center;
            }
            div#tooltip a:hover {text-indent:0;}
            #tooltip button { border-radius: 50%;
                border: 1px solid black;
                padding-top: 3px; }
</style>

HTML:

<div id="tooltip">
            <a href=""><button id="button" >?</button>
                <span>This is an example of some hover text!</span>
            </a>
</div>

Answer №3

Your JavaScript function seems to be fine, but the structure of your HTML is quite messy. I reorganized the HTML structure and managed to achieve the desired functionality using the same code you provided.

<html>
    <head>
    <style type="text/css">
    #button  {
        border-radius: 50%;
        border: 1px solid black;
        padding-top: 3px;
        padding-bottom: 3px;
    }
    #info   {
        margin-left: 5%;
    }
    #help_container {
        border: 0.5px solid black;
        background-color: #efefef;
        width: 20%;
    }
    #close  {
        float: right;
        margin-top: 1%;
        background-color: #efefef;
        border: 0px solid #efefef;
    }
    #help_text  {
        margin: 5%;
        font-family: Arial;
        font-size: 15px;
    }
    </style>
    <script>
        function mOver(obj)
        {
        obj.innerHTML="<div id='help_container'><button id='close'>X</button><p id='help_text'>Help Text</p></div>"
        }

        function mOut(obj)
        {
        obj.innerHTML="<button id='button' onmouseover='mOver(this)' onmouseout='mOut(this)'>?</button>"
        }
    </script>
    </head>
    <body>
    <div>
    <button id="button" onmouseover="mOver(this)" onmouseout="mOut(this)">?</button>
    </div>
    </body>
</html>

Answer №4

If you want to manipulate a div with innerHTML using your code, you should be interacting with a button rather than a div. Here is an example of how you can achieve this:

<div id="my_div">
<button id="button" onmouseover="javascript:mOver('my_div');" onmouseout="javascript:mOut('my_div');">?</button>
</div>

To make the X button functional, you can use the following code:

<button onclick="javascript:mOut('my_div');">X</button>

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

AngularJS fails to trigger window scroll event

Although I have come across similar inquiries regarding this issue, none of the solutions have proven to be effective for me. Currently, I am working with AngularJS and I am attempting to detect the scroll event. Despite trying numerous variations to capt ...

Tips for applying CSS conditionally to content at varying nesting levels

Currently, I am working with sass and finding it challenging to modify the structure of the page easily. The layout I have in place is due to my header having varying sizes depending on the specific page users are browsing: <div class="container"> ...

Struggling to align block elements correctly after changing them to inline

I've been trying to align this paragraph while keeping the navigation menu and logo in their correct positions. I attempted to make everything inline, but that didn't work. Then I experimented with the float property, which only made things worse ...

Increase the value of a number using jQuery

When using jquery to animate a random number increment from 0001 to 1000, the issue arises when reaching the number 0077. The final number displayed is 77 instead of 0077. Is there a solution to ensure the format remains as 0077? Your help is appreciated. ...

What causes my child element to be positioned with respect to the body even though its parent is set to relative positioning?

Here is the HTML code I am working with: <html> <head></head> <body> <div id="board"> <div class="person"></div> </div> </body> </html> And here is the ...

A single background image split into several div elements

I am facing an issue regarding the background image placement in multiple divs. When I set the position to fixed, the image repeats when I resize the screen. However, changing it to absolute causes each div to have its own image. Is there a solution to fi ...

Using Axios to retrieve data from a MySQL database is a common practice in web development. By integrating Vue

I have developed another Vue.js admin page specifically for "writer" where I can display post data fetched from a MySQL database. The admin page called "admin" is functioning properly and responding with all the necessary data. The following code snippet ...

Executing the instruction to delete tailwindcss from the input.css document

Every time I execute: npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch My output.css file is stripped of most Tailwind CSS styles, only leaving a few elements intact. You can see the result in this image: https://i.sstatic.net/SXGhV.png T ...

Discrepancy in Mobile Versions

I'm currently working on creating my very first personal portfolio website. Initially, everything seemed to be displaying correctly when viewed in browser and through various mobile emulators. However, upon checking the site on my physical iPhone 5 (a ...

Re-calculating with Jquery when input is updated

I am looking for guidance on how to make the calculator recalculate based on a change in the #calcTotal input field. I have successfully calculated all fields and managed to update the #cwac field when one of the values before it changes. Here is the HTML ...

Trouble arises with the MUI 5 date picker when inputFormat is included

When I select a date from the calendar, everything works fine. However, if I set inputFormat="yyyy/MM/dd" and manually type in the date, it doesn't recognize the date format properly. Instead, it treats the input as a string like 11111111111 ...

What is the process of using AJAX, JavaScript, and HTML to submit data to a remote

I need help with sending data from an HTML page to a server. I have a JSON example below that illustrates what I want to achieve. On my HTML page, I have a question label and four options (A, B, C, D) as radio buttons. After clicking the send button, I ...

Implementing child components rendering in a React application using TypeScript

Just a little background information: I am attempting to build a carousel with pagination using ReactJS. Here is the code snippet I currently have: interface HTMLCarouselT { children: Array<JSX.Element> size: number; } const HTMLCarousel = ({ch ...

Issue with the responsiveness on smaller screens on the Website

Having some trouble with responsiveness on very small screens. Let me break it down: on extremely small screens, my containers keep shrinking until they disappear altogether and shift to the right. Despite using Bootstrap, I can't figure out why this ...

JavaScript that is subtle and lacks function parameters

Suppose you have: <div id="data" onclick="handleData(1)">Datum 1</div> and you prefer late binding instead: <div id="data">Datum 1</div> <script> $("#data").click(function() { handleData(1); }) </script&g ...

"Waiting for results with Node.js and Mongo DB is like trying to catch a

I am currently working on developing a Web Api using NodeJs and MongoDB. One issue I have encountered is that my await statements are not being awaited, leading to unexpected behavior in my code. Code async find_nearby_places(lng, lat, tag, maxDistanc ...

Sending data from Ajax to PHP and saving it in a database

Hello, I'm facing an issue. I am trying to pass a JavaScript variable to my PHP script and store it in a MySQL database but for some reason, it's not working. Below is the code I am using: JavaScript: <script type="text/javascript"> ...

jQuery did not display the alert message

A JQuery weather plugin has been successfully implemented, but there is an issue with some code not displaying the data. The problem lies in the last section of the JQuery code, where a message should be displayed to the user when the temperature exceeds a ...

Issues with CSS and HTML layering

I created a toggle switch in HTML with a label and styled it using CSS. Everything works fine when the toggle is on, but the issue arises when it's off – the label overlaps with the switch. https://i.sstatic.net/jT4oO.png https://i.sstatic.net/X7h ...

Discovering the data from every input field using jQuery

So, I've created a program that starts with one input field. By pressing the plus button, it adds new input fields with different IDs. When I press calculate, I want to save all the input field values into an array. I attempted using a for loop with . ...