The issue of jQuery CSS positioning failure in Chrome/Opera

My code is functioning correctly in IE and Firefox, but not in Opera or Chrome. Essentially, it generates a DIV that is placed right after the input field. In IE and Firefox, the new div overlaps the input, but in Opera and Chrome, it appears next to the lower right corner of the input, which is not the desired positioning. Any ideas on how to fix this?

Edit: I have attached an image showing the desired layout, which is not being achieved in Chrome and Opera. The intentional overlap is not happening in these browsers - instead, the green div is positioned at the lower right corner. Although this serves as a starting point, the position CSS class should be modifying it.

https://i.sstatic.net/WcJPP.jpg
(source: aspadvice.com)

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js " type="text/javascript"></script>
        <script type="text/javascript">
            jQuery.fn.makeDiv = function () {
                $(this).each(function () {
                    var className = "wFWn";

                    $(this).after("<div class='" + className + "'>The Div</div>");
                    var c = $(this).next("." + className);

                    var topStartPosition = $(this).outerHeight();
                    var leftStartPosition = $(this).outerWidth();
                    c.addClass('green');
                    c.addClass('position');
                    var pos = $(this).offset();
                    var iTopOffset = 0;
                    if (c.css("top") != "auto")
                        iTopOffset = parseInt(c.css("top").substring(0, c.css("top").indexOf("px")));
                    var iLeftOffset = 0;
                    if (c.css("left") != "auto")
                        iLeftOffset = parseInt(c.css("left").substring(0, c.css("left").indexOf("px")));
                    c.offset({ top: pos.top + topStartPosition + iTopOffset, left: pos.left + leftStartPosition + iLeftOffset });
                    c.css("position", "relative");
                });
                return this;
            };
            $(document).ready(function () {
                $("#txtTest2").makeDiv();
            });
        </script>
        <style type="text/css">
            .position {top: -4px; left: -100px; width: 140px; font-size: 11px; }
            .green { background-color: lime; border: solid 1px black;}
        </style>
    </head>
    <body>
        <div id="two">
            <input name="txtTest2" type="text" maxlength="10" id="txtTest2" /><br />
        </div>
    </body>
</html>

Answer №1

the issue lies in the "Position" class within the CSS, specifically overriding the top and left properties

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        jQuery.fn.makeDiv = function () {
            $(this).each(function () {
                var className = "wFWn";

                $(this).after("<div class='" + className + "'>The Div</div>");
                var c = $(this).next("." + className);

                var topStartPosition = $(this).outerHeight();
                var leftStartPosition = $(this).outerWidth();
                c.addClass('green');
                c.addClass('position');
                var pos = $(this).offset();

you can adjust the top value directly instead of using the CSS style

                var iTopOffset = -4;
               if (c.css("top") != "auto")
                    iTopOffset = parseInt(c.css("top").substring(0, c.css("top").indexOf("px")));

similarly, you can also modify the Left property without relying on the CSS

                var iLeftOffset = -100;
                if (c.css("left") != "auto")
                    iLeftOffset = parseInt(c.css("left").substring(0, c.css("left").indexOf("px")));
                c.offset({ top: pos.top + topStartPosition + iTopOffset, left: pos.left + leftStartPosition + iLeftOffset });
                c.css("position", "relative");
            });
            return this;
        };
        $(document).ready(function () {
            $("#txtTest2").makeDiv();
        });
    </script>
    <style type="text/css">

an adjustment has been made to remove the "top: -4px; left: -100px;" from the ".position { }" section

        .position { width: 140px; font-size: 11px; }
        .green { background-color: lime; border: solid 1px black;}
    </style>
</head>
<body>
    <div id="two">
        <input name="txtTest2" type="text" maxlength="10" id="txtTest2" /><br />
    </div>
</body>

Answer №2

Despite

Using jQuery to adjust the left position of an element with `position:relative` may not function properly in Chrome (works fine in IE). This could be causing the issue you are experiencing. 

However, I found that jQuery's .offset() method worked consistently across all browsers:

//jQuery('#ProgressIcon').css('left', '155');       // didn't work in chrome
var position = jQuery('#ProgressIcon').offset();
position.left += 133;       //155 210
jQuery('#ProgressIcon').offset(position);

Answer №3

To replace .after() with .appendTo() is recommended

$("<div class='" + className + "'>The Div</div>").appendTo($(MainDiv));

-update rectified a spelling mistake-

Answer №4

In October 2015, I encountered an issue where the JQuery CSS method was not working correctly in Chrome but worked fine in Internet Explorer (at least in my particular case).

In my scenario using Razor CSHTML/MVC, Chrome was failing to apply the "top style" property when using JQuery, resulting in it not being properly set in the HTML styling for the element in question. Specifically, this line of code did not function as expected in Chrome:

$("#@tileid").css({ "top": top, "left": left });

Interestingly, Chrome would recognize the 'left' setting but ignore the 'top' setting entirely.

To work around this issue, I directly manipulated the HTML which successfully resolved the problem in both IE and Chrome:

 <div id="@tileid" class="tile" style="clear:both;top:@toppx; position:absolute;left:@leftpx;">

By leveraging CSHTML variables, I was able to implement this solution. However, if you are not using CSHTML/MVC, you may consider manipulating the HTML directly as a potential workaround.

It's surprising that Chrome struggled to process such a fundamental JQuery CSS method in 2015.

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 issue arises when the jQuery $.get() method fails to deliver the expected response to the client, despite returning a status code of

I am having trouble with sending a REQUEST to a server in order to retrieve a message. I have tried using the jQuery method $.get(), and it seems to have successfully reached the server. However, I am facing an issue where I am unable to send a RESPONSE b ...

Issue with Firefox: Click event not triggered when clicking on CSS pseudo element

Check out my custom-made button: <button class="btn-close">Close alert</button> Here's the CSS styling for the button: .btn-close{ position: relative; height: 30px; border: none; background-color: #332b2a; color: #ff ...

How does jquery's removeClass function on a button continue to function smoothly even after an ajax call

Code Snippet: <span class="input-group-text"> <button type="button" class="btn btn-outline-danger btn-sm owner_button owner_check" name="owner_check" > <i class="far fa-check-circle"></i> </button> </span> ...

The modals equipped with data-dismiss="modal" and data-target="#id" do not navigate to their intended destination

Attempting to focus the input field using the modal data-target function on button click. The input field is focused, but a div called <div class="modal-backdrop in"> is created and the modal does not close properly. This prevents the user from click ...

Looking to achieve a stretch-auto-auto column layout in Bootstrap 4 - how can this be done?

Essentially, I am looking for something similar to this: https://i.sstatic.net/ss3Ir.png Can this layout be achieved using columns instead of floats? <div class="clearfix"> <div class="float-left"><button class="rounded btn btn-outline ...

On my website, two elements are stacked on top of each other

The CSS framework I am currently utilizing is Materialize Whenever I try to add a new element, it inexplicably appears below the ones above it. I did not specifically instruct it to be positioned underneath or below the cover container. Adding a z-index c ...

Tips for resolving issues with the navigation menu not appearing on the website

For more information, please visit the webpage at I am facing an issue where the dropdown menu does not show up when hovering on the Services page. The dropdown menu was created in WordPress using wp_nav_menu. There are 5 pages, including a Services page ...

The jQuery function is not functioning correctly

Currently, I am in the process of setting up an accordion menu using jQuery and CSS3. Everything is working perfectly fine so far except that the menu always opens upon page load and the code to hide it is not functioning as intended. Here's the link ...

Creating a horizontal line to the left of centered text using CSS styling

Is there a way to display a horizontal line to the left of text while keeping the text center aligned? Refer to the image below for clarification. Below is the markup I am currently using, which includes Bootstrap 4: https://i.sstatic.net/KF8WJ.png ...

Streamline Your Selector Choices

I've been having difficulty trying to streamline certain query selectors. Here's the most simplified version I could come up with. $($(".NextYearDays td[data-index='1'], .NextYearDays td[data-index='2'] , .NextYearDays td[dat ...

The AJAX data submission did not go through as expected

I am facing an issue with two files on my site - home.php (view) and home.php (controller). In the home.php (view) file, I have a jQuery function that sends an AJAX request based on the W3 example. However, in the home.php (controller) file, the PHP variab ...

Guidance on showing or hiding HTML elements using jQuery upon the user clicking a <span> tag

My current project involves toggling the visibility of an HTML table when a user clicks on a specific menu item (a span tag), and then passing the data to an ajax function for GET/POST requests to a PHP file. The end goal is to display a comparison table b ...

What is the best way to make multiple carousels work simultaneously?

For example, imagine two carousels occupying the same location but one is always hidden. There are two buttons above to toggle either carousel on: <div class="row"> <div class="col-lg-12"> <div class="ca ...

Security measures within the browser are blocking access to the same-domain Ajax request made using jQuery, resulting in an "Access is

While attempting to submit a form using jQuery's $.post method, I am encountering the SCRIPT5: Access is denied. error specifically in Internet Explorer. Despite the common belief that this error is linked to cross-domain requests, my own request does ...

Error message: jQuery AJAX request fails due to permission denial issue on Internet Explorer

I am facing a major challenge on my website. I have implemented AJAX to update the content of a DIV, which works perfectly on all pages except for some links under the Portfolio tab. The links for "photography", "interactive", "print", and "traditional" tr ...

Is there a way to automatically trigger an Anthem.NET button click event upon page load in ASP.NET?

My goal is to initiate the loading of an ASP.NET page followed by triggering a server-side event that will update some HTML on the client side. The event is associated with an Anthem.NET imagebutton control, so the most obvious approach would be to simply ...

Is it possible for Jquery to directly retrieve the form input without the need for a SET button in the script?

I have a script that functions as a basic countdown. All you need to do is enter a number, press the SET button, and click START for the countdown to begin. Although I primarily use this script in the gym, I often forget to hit the SET button after enteri ...

Unable to implement the reordering of a list using jQuery's AJAX functionality

Currently, I am utilizing jQuery ajax to dynamically load a new PHP query that changes the order of a list. However, despite my efforts, nothing seems to be happening. Here is the specific query I have implemented in load.php: $stm = $conn->prepare(&ap ...

``Modeling CSS Classes Using the Adjacent Sibling

As a coding novice, I challenged myself to rebuild my WordPress site using HTML, CSS, and JavaScript. In my quest for the best way to create a responsive navigation bar, I stumbled upon an example on W3Schools. My dilemma lies in how to handle Adjacent Cl ...

Using Symfony2 with Jquery UI-Tabs for Enhanced User Interface Experience

Whenever I visit the following page, I am able to contact them directly with no issues. http://www.mysite.com/app_dev.php/comments/22 This page contains a basic text form element and a series of comments related to thread 22. I can also submit a new comm ...