Step-by-step guide to creating a pop-up div that appears on hover and remains visible when clicked

I'm trying to figure out how to make a popup appear when the mouse hovers over it and then stay visible when clicked on. The issue I'm facing is that currently, the popup disappears when the mouse moves away from it. How can I modify the code so that the popup remains visible after being clicked? Here is what I have so far:

HTML

<div id="pop1" class="popbox">
    <h2>Job Info Search</h2>
    <h2>WRKNo : <input type="text"  /></h2>
    <h2>Result</h2>
    <p>Customer Name : <input type="text"  /></p>
    <p>Caller Number : <input type="text"  /></p>
    <p>Complosed : <input type="text"  /></p>
    <p>Cate : <input type="text"  /></p>
    <p>Det : <input type="text"  /></p>
    <p>Feedback : <input type="text"  /></p>
    <p>WRKNo : <input type="text"  /></p>
</div>




This is a popbox test.  <a href="#" class="popper" data-popbox="pop1">Hover here</a> to see how it works.

CSS

.popbox {
    display: none;
    position: absolute;
    z-index: 99999;
    width: 400px;
    padding: 10px;
    background: #EEEFEB;
    color: #000000;
    border: 1px solid #4D4F53;
    margin: 0px;
    -webkit-box-shadow: 0px 0px 5px 0px rgba(164, 164, 164, 1);
    box-shadow: 0px 0px 5px 0px rgba(164, 164, 164, 1);
}
.popbox h2
{
    background-color: #4D4F53;
    color:  #E3E5DD;
    font-size: 14px;
    display: block;
    width: 100%;
    margin: -10px 0px 8px -10px;
    padding: 5px 10px;
}

Javascript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script>
$(function() {
    var moveLeft = 0;
    var moveDown = 0;
    $('a.popper').hover(function(e) {

        var target = '#' + ($(this).attr('data-popbox'));

        $(target).show();
        moveLeft = $(this).outerWidth();
        moveDown = ($(target).outerHeight() / 2);
    }, function() {
        var target = '#' + ($(this).attr('data-popbox'));
        $(target).hide();
    });

    $('a.popper').mousemove(function(e) {
        var target = '#' + ($(this).attr('data-popbox'));

        leftD = e.pageX + parseInt(moveLeft);
        maxRight = leftD + $(target).outerWidth();
        windowLeft = $(window).width() - 40;
        windowRight = 0;
        maxLeft = e.pageX - (parseInt(moveLeft) + $(target).outerWidth() + 20);

        if(maxRight > windowLeft && maxLeft > windowRight)
        {
            leftD = maxLeft;
        }

        topD = e.pageY - parseInt(moveDown);
        maxBottom = parseInt(e.pageY + parseInt(moveDown) + 20);
        windowBottom = parseInt(parseInt($(document).scrollTop()) + parseInt($(window).height()));
        maxTop = topD;
        windowTop = parseInt($(document).scrollTop());
        if(maxBottom > windowBottom)
        {
            topD = windowBottom - $(target).outerHeight() - 20;
        } else if(maxTop < windowTop){
            topD = windowTop + 20;
        }

        $(target).css('top', topD).css('left', leftD);


    });

});
</script>

Can anyone suggest a solution for this functionality?

Answer №1

Check out this code snippet:

$('a.popper').hover(function (e) {    
    var target = '#' + ($(this).attr('data-popbox'));
    $(target).show();
    moveLeft = $(this).outerWidth();
    moveDown = ($(target).outerHeight() / 2);
}, function () {
    var target = '#' + ($(this).attr('data-popbox'));
    if (!($("a.popper").hasClass("show"))) {
        $(target).hide(); //ensure popup is not hidden when clicked
    }
});
$('a.popper').click(function (e) {
    var target = '#' + ($(this).attr('data-popbox'));
    if (!($(this).hasClass("show"))) {
        $(target).show();
    }
    $(this).toggleClass("show");
});

View the FIDDLE here.

Answer №2

Implement the click function in jQuery, such as using $('a.popper').click(); and providing parameters to display the popup when clicking, like you currently do with the hover method and mouseover method.

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

The npm package for google-spreadsheet.js is experiencing issues and is not functioning correctly when trying to replicate the GitHub

After attempting to implement the basic example code provided at https://github.com/theoephraim/node-google-spreadsheet, I encountered an issue. For instance: const { GoogleSpreadsheet } = require('google-spreadsheet') const creds = require(&apo ...

Check to see if two words are identical in PHP

Could you please check the word I've written in the text field? If the two words are the same, I should receive a message saying "They are the same." <?php function array_random($arr, $num = 1) { shuffle($arr); $r = array(); for ($i = ...

The for loop does not pause for asynchronous code to complete

The for loop in my code has a function call that contains async code. However, the issue is that the for loop does not wait for the async code to return before continuing with the iterations. The function aFunctionThatRunsAsync is from a library that I ca ...

A comprehensive guide on publishing an application to Heroku using MongoDb/Mlab

I am encountering difficulties in deploying my Node.JS application to Heroku. I suspect that the issue lies with the database, but I cannot pinpoint the exact problem. I have attempted to switch from MongoDB Atlas to Mlab in hopes of resolving the issue, h ...

Show a notification every time an SQL update is completed successfully

Utilizing PHP, I am updating the item table by iterating through a result set. while (!$rs->EOF) { $conn->Execute("UPDATE [table] SET qty='".$quantity."' WHERE locn ='".$locn."' AND pdln ='".$pdln."'") ...

Deciding on excluding empty key:value pairs from an object for various filtering needs

One of the features in my app allows users to filter results by "blood group" and "city", along with other areas. The information is retrieved from a database using Axios for Vuejs, incorporating query strings within the URL. For example: http://example.co ...

View content from an external file within an iframe

My goal is to showcase a text file within an iframe that updates automatically every second. To achieve this, I have created a simple function: function refresh() { $("#derek").attr('src', $("#derek").attr('src')); }; The automati ...

Upon clicking the button, provide the client with the Cloudinary link

In my Next.js project, I am using Cloudinary to generate secure URLs for images. The URL is stored in the variable result.secure_url within my app/page.js file. The button functionality is defined in app/components/Cloudinary.js and imported into app/pag ...

Is it possible to set up a server with 'app' as the designated request handler?

When working with NodeJS, server creation can be done simply by using: http.createServer(function(req,res) { /* header etc. */}); However, as I delved into using express, the server was automatically created for me. Moving on to learning about sockets, I ...

Error encountered: Unexpected '<' token when trying to deploy

Trying to deploy a React app with React Router on a Node/Express server to Heroku, but encountering the following error... 'Uncaught SyntaxError: Unexpected token <' Suspecting the issue may lie in the 'catch all' route in the Expr ...

Executing jQuery code after PHP content has loaded

I am currently working on a website using the Big Commerce platform. The cart page is constructed using PHP snippets, but unfortunately, I do not have access to the PHP files. My goal is to extract the value of a span tag at a specific index and use this v ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Experiencing difficulty navigating JSON objects

I am facing an issue with a JSON structure that has the following format: [ { "coordinates": [ 75.71027043, 26.88661823 ] }, { "coordinates": [ 75.71027043, 26.88661823 ...

Displaying 100,000 sprites with a faint 0.1 opacity, utilizing see-through backgrounds and crisp antialiasing

In my current setup, I have the following key pieces of code: Renderer renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, canvas: canvas }); Textures dot: THREE.ImageUtils.loadTexture('./assets/images/dot.png') Material ...

What is the best way to modify the text color in an MUI Text Field?

I'm completely new to using MUI and React, and I've run into an issue with changing the text color in my input field. Even though I specified inputProps={{sx: { color: "CCCCCC" }}}, the text color remains black while the label and searc ...

Is there a way to set up a loop for managing four separate drop-down lists?

While the code is functioning properly, I am determined to streamline it into a loop. Unfortunately, all my attempts thus far have been unsuccessful. The code displays four drop-down lists with different Id's, but they share the same class name (optio ...

Having trouble rendering a model using OBJLoader in React Three Fiber

I'm having issues with rendering an .obj file in my React project using the OBJLoader and useLoader() hook from React Three Fiber. Despite ensuring that my file path is correct and wrapping the Model component in Suspense tags, I am still encountering ...

Guide to embedding an iframe generated with JavaScript into a React component

I'm currently working on developing an app that will utilize an iframe. The goal is to have controllers in place to adjust the style of the iframe and add text to it, essentially creating a preview function. I've been attempting to use Javascript ...

Customize div styles according to the website domain

I want to dynamically change the header of my website based on whether it is in dev QA or production environment. Below is the HTML code: <div id="wrapper"> <form id="form1" runat="server"> <div class="wrapper"> <div> ...

Is there a way to transform this Json array into a format that JQuery can interpret easily?

Having a bit of trouble with this issue. I'm not entirely sure how to get it working correctly. According to Firebug, the Json object (or possibly array) from my ajax request appears as follows: { "jsonResult": "[ {\"OrderInList\":1}, ...