The positioning of elements varies between mobile devices and desktop screens

Recently, I've been playing around with jQuery and created a popup menu of sorts. The positioning of the popup div is calculated when it's shown or when the window is resized.

I've noticed that the positioning doesn't work correctly on mobile devices; the popup div appears too far to the right.

Why does this happen? Why is the popup div displayed differently on mobile devices compared to desktop?

Here's an example that works well on a desktop and two images showing how things go awry on a mobile device:

https://i.sstatic.net/zHylB.png https://i.sstatic.net/4MaXl.png

            $(document).ready(function () {
                $(".button").mouseover(function () {
                    showPopup();
                });
        
                var timeout;
                $(".popup").mouseleave(function () {
                    timeout = setTimeout(function () {hidePopup(500);}, 500);                    
                });
                
                $(".popup").mouseenter(function () {
                    clearTimeout(timeout);                   
                });
                
                $(".button").click(function () {
                    togglePopup();
                });
                
                $(".closebutton").click(function () {
                    hidePopup(0);
                });
                
                $(window).resize(function () {
                    positionPopup();
                });
                                
            });
            
            function positionPopup() {
                var pos = $(".button").offset();
                var h = $(".button").height();
                var w = $(".button").width();
                
                var widthPopUp = $(".popup").width();
                var heightPopUp = $(".popup").height();
                
                $(".popup").css({left: pos.left -  widthPopUp - 20 - 3 + w, top: pos.top + h + 10});         
            }
            
            function showPopup() {
                positionPopup();
                $(".popup").fadeIn(300);
            }
            
            function hidePopup(delay) {
                if (typeof(delay) === 'undefined') {
                    delay = 1000;
                }
                $(".popup").fadeOut(delay);
            }
            
            function togglePopup() {
                positionPopup();
                $(".popup").toggle();
            }
* {
    box-sizing: border-box;
}

html, body {
    margin: 0px;
    padding: 0px;
}

.container {
    width: 500px;
    border: 1px solid black;
    margin: 50px auto;
    height: auto;
    position: relative;    
    border-radius: 2px;
    padding: 10px;
    padding-top: 25px;
}

.buttonholder {
    height: 20px;
    width: 20px;
    text-align: center;
    line-height: 15px;
    right: 0px;
    top: 0px;
    position: absolute;
    margin: 3px;
    display: block;
}

.button {
    cursor: pointer;
}

.popup{
    border: #DDDDDD 1px solid;
    width: 200px;
    height: 40px;
    display: none;
    position: absolute;
    background-color: white;
    padding: 10px;
    border-radius: 2px;
}

.closebtnholder {
    position: absolute;
    top: 0px;
    right: 0px;
    margin: 3px;
    text-align: center;
}

.closebutton {
    cursor: pointer;
    font-size: 10pt;
}

.popup::after {
  border-bottom: 8px solid #DDDDDD;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  width: 0;
  height: 0;
  content: "";
  display: block;
  position: absolute;
  top: -8px;
  left: 184px;
}
<!DOCTYPE html>

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="layout.css" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>        
     </head>
     
    <body>
        <div class="container">
            
            <div class="buttonholder">
                <div class="button">[?]</div>
            </div>
            
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the 
            industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and 
            scrambled it to make a type specimen book. It has survived not only five centuries but also the leap 
            into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the 
            release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing 
            software like Aldus PageMaker including versions of Lorem Ipsum.
            
        </div>
        
        <div class="popup">
            <div class="closebtnholder">
                <div class="closebutton">[x]</div>
            </div>
            <a href="http://google.be">google</a>
        </div>
        
        <div class="triangle">
            
        </div>
        
    </body>
</html>

Answer №1

There are several solutions to address this issue. One option is to utilize a responsive CSS framework like Twitter Bootstrap, or you could create a new stylesheet to override the existing one specifically for mobile devices.

Here is an example using PHP:

<link rel="stylesheet" type="text/css" href="/css/main.css" />
<?php
$isMobile = (bool)preg_match('#\b(ip(hone|od|ad)|android|opera m(ob|in)i|windows (phone|ce)|blackberry|tablet'.
    '|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp|laystation portable)|nokia|fennec|htc[\-_]'.
    '|mobile|up\.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\b#i', $_SERVER['HTTP_USER_AGENT'] );
if($isMobile){ ?>
    <link rel="stylesheet" type="text/css" href="/css/mobile.css" />
<?php } ?>

In the 'mobile.css' file, you can define the styling for your mobile pages.

.container {
width: 300px;  //this will override the previous settings
}

While this is a quick fix, I recommend familiarizing yourself with a responsive framework for more efficient long-term management of your design.

Answer №2

Just a minor tweak to your code snippet

$(document).ready(function () {
$(".button").mouseover(function () {
showToolTip();
});

var timer;
$(".tooltip").mouseleave(function () {
timer = setTimeout(function () {hideToolTip(500);}, 500);
});

$(".tooltip").mouseenter(function () {
clearTimeout(timer);
});

$(".button").click(function () {
toggleToolTip();
});

$(".closebutton").click(function () {
hideToolTip(0);
});
});

function showToolTip() {
$(".tooltip").fadeIn(300);
}

function hideToolTip(delay) {
if (typeof(delay) === 'undefined') {
delay = 1000;
}
$(".tooltip").fadeOut(delay);
}

function toggleToolTip() {
$(".tooltip").toggle();
}
* {
    box-sizing: border-box;
}

html, body {
    margin: 0px;
    padding: 0px;
}

.container {
    border: 1px solid black;
    margin: 50px auto;
    height: auto;
    position: relative;
    border-radius: 2px;
    padding: 10px;
    padding-top: 25px;
}
@media only screen and (min-width: 540px) {
.container {
width: 500px;
}
}
@media screen and (max-width: 539px) {
.container {
width: calc(100% - 20px);
margin: 20px auto;
}
}

.buttonholder {
    height: 20px;
    width: 20px;
    text-align: center;
    line-height: 15px;
    right: 0px;
    top: 0px;
    position: absolute;
    margin: 3px;
    display: block;
}

.button {
    cursor: pointer;
}

.tooltip{
    border: #DDDDDD 1px solid;
    width: 200px;
    height: 40px;
    display: none;
    position: absolute;
    background-color: white;
    padding: 10px;
    border-radius: 2px;
}

.closebtnholder {
    position: absolute;
    top: 0px;
    right: 0px;
    margin: 3px;
    text-align: center;
}

.closebutton {
    cursor: pointer;
    font-size: 10pt;
}
.popup {
position: absolute;
top: 2em;
right: 0;
}
.popup::after {
border-bottom: 8px solid #DDDDDD;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
width: 0;
height: 0;
content: "";
display: block;
position: absolute;
top: -8px;
left: 184px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

<div class="buttonholder">
<div class="button">[?]</div>
</div>

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's 
standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make 
a type specimen book. It has survived not only five centuries but also the leap into electronic typesetting, remaining 
essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, 
and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

<div class="tooltip">
<div class="closebtnholder">
<div class="closebutton">[x]</div>
</div>
<a href="http://google.be">google</a>
</div>
</div>

Answer №3

Insert a media query into your CSS code as shown below:

@media (max-width: 480px){
   .container {
    width: calc(100% - 50px);
    border: 1px solid black;
    margin: 50px auto;
    height: auto;
    position: relative;    
    border-radius: 2px;
    padding: 10px;
    padding-top: 25px;
} 

For further reference, you can view the fiddle at https://jsfiddle.net/DIRTY_SMITH/rh6w934n/

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

How can we effectively monitor and record deleted items on the user interface to ensure they are accurately stored on the server?

I am currently developing a system in which teachers can manage the enrollment of students in their classes. The user interface allows them to add or remove students, as well as update details such as the class name and room number. Right now, I am implem ...

Utilizing the @page CSS rule in Vue.js: A step-by-step guide

I am facing an issue with printing a specific page in landscape mode. Here is the code snippet I have been using: @page { margin: 0; size: A4 landscape; } The problem is that this style rule affects all pages in my application because all style se ...

When attempting to submit data, the Magnific Popup page is restored to its default format

I am facing an issue with my Magnific Popup page: function dataLink(){ $.magnificPopup.open({ items: { src: 'datapage.html', type: 'ajax' }, closeOnContentClick : false, clos ...

The function .val() is not a recognized method

hello everyone here is the section of my HTML code: <div class="radio"> <input type="radio" name="certain" id="oui" value="oui"/> <label for="oui"> oui </label> <br /> <input type="radio" name="certain" id=" ...

Using JavaScript code to sift through and eliminate irrelevant data

Recently, I started learning about angular js and came across a link from which I need to extract a list of names and ids. I successfully retrieved the list in json format, but now I need to filter out unwanted items. The criteria for filtering is based ...

What are the consequences of not using removeEventListener in JavaScript?

Currently, I am implementing event listeners to determine if the device has touch capabilities. I would like these event listeners to remain active even after the page is reloaded. Is it necessary to remove the event listeners using removeEventListener(&a ...

Chart.js malfunctioning - Uncaught reference error:

In an attempt to visualize time series data using chart.js, I am encountering some issues. The data is extracted from a psql database, converted to JSON format, and then passed as a parameter to a JavaScript function for rendering the chart. Although the ...

"Keep the ajax requests flowing, don't forget about the previous

Utilizing the Bootstrap framework version 3.3.7, I am faced with the following code: $('#field_submit').click(function() { //omitted irrelevant parts if (counter == 0) { //no errors encountered, form can be submitted ...

Steps for pulling information from the database and presenting it in a text box for users to edit

I'm struggling with a webpage that should allow users to update data from the database, but for some reason, the data is not displaying in the textbox. How can I make it show up correctly? Currently, on my webpage, users have to manually input all th ...

Adjust the width of the <li> element based on the quantity of its children

If the number of list items can be changed dynamically, how can I adjust the width of each item so that the total width is always 100%? Here is an example code snippet: <nav> <ul> <li>A</li> <li>B</li> &l ...

Using node.js to import functions from another file

The code below is what I currently have: // app.js var exports = module.exports = {}; module.exports = function () { var exported = {}; .. exported.myFunction = function (data, callback) { .. } . ...

troubleshooting problems with feathers.JS using the npm start command

After developing two separate feathersJS applications, I encountered a situation where running npm start resulted in two unique types of errors for each app. How can I go about resolving this issue? View image here https://i.stack.imgur.com/RrsGW.pnghtt ...

Pass the value from JavaScript to PHP

I am looking to insert a JavaScript value into PHP: var temp = $('#field_id').val().charAt(0); The 'temp' variable returns values ranging from 1 to 4. var value = "<?php echo $variable[temp]['id']; ?>"; How can I re ...

TypeScript Yup schema validation combined with the power of Type Inference

I currently have a unique data structure as shown below: type MyDataType = | { type: "pro"; content: { signedAt: string; expiresOn: string }; } | { type: "default" | "regular"; content: { signed ...

Stepping up Your Next.js Game with the Razorpay Payment Button Integration

When using the Razorpay payment button on a website, it provides a code snippet like this: <form> <script src = "https://cdn.razorpay.com/static/widget/payment-button.js" data-payment_button_id = "pl_FNmjTJSGXBYIfp" data ...

Problem with Jquery Colorbox in firefox

I am using JavaScript to dynamically populate anchor links in a repeater and displaying them in a colorbox iframe. This functionality is working well in IE7, Safari, and Chrome, but encountering an issue in Firefox (version 14.1). In Firefox, the links ar ...

What is the best way to initiate a function upon each page load?

(Apologies in advance for any English mistakes) Hello everyone, I am currently developing a simple Chrome extension to edit certain graphics and text fields on a website (Freshdesk) that cannot be modified directly on the site due to proprietary code. ...

Scrollbar malfunction in Angular and Bootstrap主 The main scrollbar in Angular and Bootstrap is un

I am currently facing an issue with my Angular app using Bootstrap 5. The main html/body scrollbar does not work when elements overflow the view. I have tried various solutions such as setting a fixed height, adjusting overflow-y to scroll or auto for body ...

Moving the vertical tab panel container div to the center of the main div for Easytabs - adjusting size and positioning

Hey there: I've been experimenting with the "easytabs" jQuery plugin to create vertical tabs positioned along the right edge of the main div containing all the content of my web page. My CSS skills are lacking. Although I've made good progress, ...

Are Gatsby Server-Side Rendering APIs and Next.js SSR the equivalent in functionality?

After mastering Gatsby Js for building an ecommerce website using the SSR method, I am now contemplating between sticking with Gatsby or switching to Next for future scalability as web technology advances and user base expands. Which option would be bett ...