Utilize JavaScript to trigger a div pop-up directly beneath the input field

Here is the input box code:

<input type='text' size='2' name='action_qty' onmouseup='showHideChangePopUp()'>

Along with the pop-up div code:

<div id='div_change_qty' name='div_change_qty' style='display:none;width:200px;height:200px;position:absolute;z-index:10;background:darkgray' >
    <table width='100%' height='100%'>
        <tr><td width='20%'></td><td>Increase</td></tr>
        <tr><td width='20%'></td><td>Decrease</td></tr>
        <tr><td width='20%'></td><td>Move Items</td></tr>
        <tr><td width='20%'></td><td>Change Status</td></tr>
    </table>    
</div>

The JavaScript function defined as:

function showHideChangePopUp(e){

        //alert('here')
        if ( event.clientX ) { // Grab the x-y pos.s if browser is IE.
            CurrentLeft = event.clientX + document.body.scrollLeft;
            CurrentTop  = event.clientY + document.body.scrollTop;
        }
        else {  // Grab the x-y pos.s if browser isn't IE.
            CurrentLeft = e.pageX ;
            CurrentTop  = e.pageY ;
        }  
        //if ( CurrentLeft < 0 ) { CurrentLeft = 0; };
        //if ( CurrentTop  < 0 ) { CurrentTop  = 0; };  

        document.getElementById('div_change_qty').style.display = 'block';
        document.getElementById('div_change_qty').style.top = CurrentTop ;
        document.getElementById('div_change_qty').style.left = CurrentLeft ;

        return true;
    }

When clicking inside the input box, the goal is to position the div popup directly below it. However, the current function doesn't achieve this specific positioning. How can the JavaScript function be modified to place the div below the input box upon click?

Answer №1

Initially, we all misunderstood the original post to be about how to display or hide the div.

Below is the code that positions the div directly under the input box using the getClientRects method of the input element:

function showHideChangePopUp(e){
  var div= document.querySelector('#div_change_qty');
  var inp= document.querySelector('#action_qty');
  var rect= inp.getClientRects();
  div.style.display= 'block';
  div.style.left= rect[0].left+'px';
  div.style.top= rect[0].bottom+'px';
}
<div id='div_change_qty' name='div_change_qty' style='display:none;width:200px;height:200px;position:absolute;z-index:10;background:darkgray' >
  <table width='100%' height='100%'>
    <tr><td width='20%'></td><td>Increase</td></tr>
    <tr><td width='20%'></td><td>Decrease</td></tr>
    <tr><td width='20%'></td><td>Move Items</td></tr>
    <tr><td width='20%'></td><td>Change Status</td></tr>
  </table>
</div>

<input type='text' size='2' name='action_qty' id="action_qty" onmouseup='showHideChangePopUp()'>

Original Post

It's generally recommended to avoid including JavaScript within your HTML.

The following code assigns an onmouseup event handler to the input element, which toggles the visibility of the div.

An onblur event handler is also attached to make the div disappear when you exit the input field.

var qty= document.querySelector('#qty');

qty.onmouseup= function(e) {
  var div= document.querySelector('#div_change_qty');
  div.style.display= div.style.display==='block'?'none':'block';
}

qty.onblur= function(e) {
  var div= document.querySelector('#div_change_qty');
  div.style.display= 'none';
}
#div_change_qty{display:none;}
<input type='text' size='2' name='action_qty' id="qty">

<div id='div_change_qty' name='div_change_qty' style='display:none;width:200px;height:200px;position:absolute;z-index:10;background:darkgray' >
    <table width='100%' height='100%'>
        <tr><td width='20%'></td><td>Increase</td></tr>
        <tr><td width='20%'></td><td>Decrease</td></tr>
        <tr><td width='20%'></td><td>Move Items</td></tr>
        <tr><td width='20%'></td><td>Change Status</td></tr>
    </table>    
</div>

<input>

Answer №2

Do you like this?

function displayHidePopUp(){
  document.getElementById('div_change_qty').style.display='block'?'block':'none';
  
  }
#div_change_qty{display:none;}
<input type='text' size='2' name='action_qty' onmouseup='displayHidePopUp()'>

<div id='div_change_qty' name='div_change_qty' style='display:none;width:200px;height:200px;position:absolute;z-index:10;background:darkgray' >
    <table width='100%' height='100%'>
        <tr><td width='20%'></td><td>Increase</td></tr>
        <tr><td width='20%'></td><td>Decrease</td></tr>
        <tr><td width='20%'></td><td>Move Items</td></tr>
        <tr><td width='20%'></td><td>Change Status</td></tr>
    </table>    
</div>

Answer №3

Implementing jQuery

function togglePopUp(){
    $(this).append($("#quantity_change").html());
} 

Answer №4

I made enhancements to Billy's response by ensuring the div appears when focused and disappears when blurred. I presented two versions: one using pure JavaScript and the other utilizing jQuery.

function showHideChangePopUp(m) {
    var disp = m === 'hide' ? 'none' : 'block';
    document.getElementById('div_change_qty').style.display = disp;
}
function showHideChangePopUpjQ(m) {
    var disp = m === 'hide' ? 'none' : 'block';
    $('#div_change_qty').css("display", disp);
}
#div_change_qty{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Using pure JavaScript:</p>
<input type='text' size='2' name='action_qty' onfocus='showHideChangePopUp("show")' onblur='showHideChangePopUp("hide")'>
<p>Using jQuery:</p>
<input type='text' size='2' name='action_qty' onfocus='showHideChangePopUpjQ("show")' onblur='showHideChangePopUp("hide")'>

<div id='div_change_qty' name='div_change_qty' style='display:none;width:200px;height:200px;position:absolute;z-index:10;background:darkgray' >
    <table width='100%' height='100%'>
        <tr><td width='20%'></td><td>Increase</td></tr>
        <tr><td width='20%'></td><td>Decrease</td></tr>
        <tr><td width='20%'></td><td>Move Items</td></tr>
        <tr><td width='20%'></td><td>Change Status</td></tr>
    </table>    
</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

Ways to modify CSS using JavaScript

Can anyone assist me with a custom CSS code that I found? It looks like this: header.type-2:not(.fixed-header) nav>ul>li>a{ color:#000; } I've been trying to change the color to #fff using JavaScript, but haven't had any success yet. ...

Issue with this.setState() not updating value despite not being related to asynchronous updates

Just a quick note, this specific question does not involve any asynchronous update problem (at least, as far as I can tell). I currently have a class component with the following code snippet (simplified for clarity on the main issue): constructor(props ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

Error message: NodeJS express unknown function or method get()

Currently, I am facing an issue while working with express and Pug (Jade) to render a page as the get() function is returning as undefined along with warnings... I followed these steps: npm install express --save npm install pug --save Here's a sn ...

What is the proper way to include a parameter in an ASP onclick function within a table row?

Below is a table row declared within a listview: <tr onclick="<%= _jsPostBackCall %>;" /> When calling a postback method on the backend, I need to retrieve the tr index: public void RaisePostBackEvent(string eventArgument) { ...

ajaxform is not providing the correct response

There is a form below that logs into Instagram based on the response it receives. If the login is successful (returns "ok"), then it shows success, otherwise it should display an error state. However, in my case, it always returns a null state for some un ...

Having difficulty placing a marker using google-maps-react

import {Map, GoogleApiWrapper} from 'google-maps-react' var React = require('react') class GoogleMapContainer extends React.Component { render() { return( <Map google={this.props.google} sty ...

The combination of two equal height elements with absolutely positioned child elements

I have a website that features a side-bar navigation and a main content pane, both enclosed within a container element. The content has its own unique background styling, while the menu adopts the background of the parent container. In situations where th ...

What is the best way to set the date defaultValue to be empty?

I've developed a basic radio button to display an additional input field when the user chooses yes. I also created a function that will clear the fields if the user selects no. schema.ts: const formSchemaData = z.object({ doesHaveDryRun: z.enum( ...

Using Jquery to select elements with specific text using the :

I am trying to execute 'action one' when the anchor variable includes the word 'image'. If it does not include that specific text, then 'action two' should be executed instead. var clickedImage = $('.header ul li') ...

I keep encountering the error message "$(".dropdown-toggle").dropdown is not a function" while attempting to use Dropdowns with Jade and Bootstrap

I am attempting to implement a Bootstrap dropdown in my Jade layout. However, I keep encountering an error when trying to run $(".dropdown-toggle").dropdown in my Jade file: $ is undefined $(".dropdown-toggle").dropdown is not a function What could be ...

Even after unsubscribing with mqtt.js, the old listener continues to receive messages

Currently, I am utilizing mqtt.js to receive websocket data from an MQTT server. The subscription process is functioning properly, but the challenge lies in changing the topic dynamically by modifying the websocket configuration. The issue arises when, eve ...

Mocking in AngularJS: Utilizing the same service with varied functions for unit testing with Jasmine

Exploring a new service, Service A, with various functionalities: The snippet of application code is as follows: angular.module('app').factory('ServiceA', function() { var ServiceA = { _retryItem: null, retryItem: ...

Tips for implementing event handlers on dynamically generated li elements in VueJS

Creating multiple ul elements using v-for in the following way <div v-for="item in info"> <ul> <li><a>{{item.number}}</a></li> <li><a>{{item.alphabet}}</a></li> </ul> </div&g ...

Utilizing a dynamic URL to set the background image of a div element (with the help of

Currently, I am in the process of designing a user registration page that allows users to input an image URL and view a preview of the image within a designated div. The div already contains a default image set by a specific class. The HTML code for displa ...

Received TypeError: Unable to call reset function - issue clearing input field post ajax request

Having Trouble Clearing Input Fields After AJAX Request: $.ajax({ type: "POST", url: "river_flow.php", data: { username: $("#username").val(), idv:$("#idv").val(), comment: $("#comment").val()}, cache: false, success: function(da ...

Encountering 404 Error in Production with NextJS Dynamic Routes

I'm currently working on a next.js project that includes a dynamic routes page. Rather than fetching projects, I simply import data from a local JSON file. While this setup works well during development, I encounter a 404 error for non-existent pages ...

Link a YAML file with interfaces in JavaScript

I'm currently learning JavaScript and need to convert a YAML file to an Interface in JavaScript. Here is an example of the YAML file: - provider_name: SEA-AD consortiumn_name: SEA-AD defaults: thumbnail Donors: - id: "https://portal.brain ...

Viewing all album titles simultaneously using the Flickr API

After trying a different approach due to lack of responses to my previous question, I am still facing the same issue. My code successfully retrieves all album names and corresponding photos from Flickr API, but it displays all album names at once followed ...

What are some strategies for disregarding global CSS styles?

I am facing an issue on my html page with a specific div structure. The <div id="container">/* lots of nested html with elements like div, ul, li etc */</div> is causing some trouble in my global css file called style.css. The style. ...