The challenge of aligning div elements efficiently with CSS and jQuery

I have a fixed div positioned on the page using CSS. Another div is dynamically generated and added to the form in the center of the page when a click event occurs on the document.

The issue arises when I click on the document to add the dynamic div, its position is correct but the static div's position changes unexpectedly. I am unsure why this is happening. Here is my code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
        $(document).ready(function () {
            $(document).click(function (e) {
                // Check for left button click
                if (e.button == 0) {
                    $('form').append('<div id="dvfloat" class="float_div">Welcome</div>').center().fadeIn('slow');
                }
            });

            jQuery.fn.center = function () {
                this.css("position", "absolute");
                this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) +
                                                $(window).scrollTop()) + "px");
                this.css("left", Math.max(0, (($(window).width() - this.outerWidth()) / 2) +
                                                $(window).scrollLeft()) + "px");
                return this;
            }
        });
    </script>
<style type="text/css">
.login_div {
    background-color: Yellow;
    margin-left: 50px;
    position: absolute;
    width: 100px;
}
.float_div {
    background-color: Green;
    width: 100px;
    height:50px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
    <div id="static_dv" class="login_div"> hi how r u ? </div>
</form>
</body>
</html>

Please test my code to observe the issue. The static div named "static_dv" repositions when clicking on the document without any explicit code causing it. I would appreciate any suggestions on fixing this unexpected behavior. Thank you

Answer №1

Instead of just centering the newly created DIV, you should center the entire form. Make this slight adjustment:

$('form').append('<div id="dvfloat" class="floating_div">Hello</div>').fadeIn('slow');
$('#dvfloat').center();

Answer №2

Your div is located within a form element, when you modified the position of the form in your javascript code, it affected all the content inside as well.

Here is a suggestion to try:

 var div = $('<div id="dvfloat" class="float_div">Welcome</div>');
 $('FORM').append(div)
 div.center().fadeIn('slow');

In order to set the position of the div, remember that using ($TAG).append($someTag) will return $TAG, so by setting the central position for $TAG, you are effectively positioning the div itself.

Answer №3

Try out the following code snippet: When you use "this" in your code, it is referencing the form element, which may prevent it from functioning properly due to changes in the form's position. To rectify this issue, below is an updated version of the code that makes reference to the div instead.

$(document).ready(function() {
    $(document).click(function(e) {
        // Check for left button click
        if (e.button == 0) {
            $('form').append('<div id="dvfloat" class="float_div">Welcome</div>').center().fadeIn('slow');
        }
    });

    jQuery.fn.center = function() {
        this.find('.float_div').css("position", "absolute");
        this.find('.float_div').css("top", Math.max(0, (($(window).height() - this.find('.float_div').outerHeight()) / 2) + $(window).scrollTop()) + "px");
        this.find('.float_div').css("left", Math.max(0, (($(window).width() - this.find('.float_div').outerWidth()) / 2) + $(window).scrollLeft()) + "px");
        return this;
    }
});​

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 I calculate multiplication using values from dynamic text fields with Jquery/Javascript?

I am looking to create a functionality where textfield1 and textfield2 values are multiplied together to get the result displayed in textfield3. Here is an example scenario with 4 textfields: textfield1 * textfields2 = txtfield3 textfield1 * textfield2 ...

What is the best way to remove a scrolling event handler from a particular element or class in JavaScript?

My goal is to set up a Table of Contents (TOC) in Obsidian that remains visible as you scroll through the page. Everything functions properly until you reach about halfway down the page, at which point the TOC mysteriously vanishes. #TOC, .TOC { posit ...

Creating universal CSS for all platforms

Seeking assistance in making this Chrome CSS code compatible across different platforms. It currently does not function properly in Firefox and is completely non-functional in IE8. Your help is greatly appreciated, thank you for taking the time to read. . ...

Transferring Live Information Between Two Controllers

How can I transfer the 'header' and 'content' from a controller's $scope element (specifically the 'header' and 'content') to another page that is redirected to upon clicking a button? The current setup involve ...

Is there a way to ensure that my text is centered on top of an image while maintaining responsiveness?

I'm trying to make the text adjust its center to the height of an image that changes size when the page is resized. Here's what I have so far: HTML <section id="eyeCatcher"> <div id="catchContainer" > <div id="eyeCatchQ ...

Shades of Grey in Visual Studio Code

Whenever I use VSC, I notice these odd grey boxes that appear in my editor. They seem to be dynamic and really bother me. Interestingly, switching to a light theme makes them disappear. However, I prefer using a dark theme and haven't been able to fin ...

Retrieve the Content-Type header response from the XHR request

My intention is to check the header content type and see if it is text/html or text/xml. If it is text/html, then it indicates an error that I need to address before moving forward. ...

Fetching Data Tables via Ajax Request

I'm attempting to retrieve data from a database using Jquery DataTable, but I keep encountering this error message: "DataTables warning: table id=tblBindData - Cannot reinitialise DataTable." function BindData() { $("#tblBindData").DataTab ...

Adjust the Size of Bootstrap 4 Dropdown Caret Icon

Currently, I am using the Bootstrap v4 framework on my HTML page. I am looking to resize or increase the caret size in my dropdown list. Does anyone have any tips on how to accomplish this? https://i.sstatic.net/kCNPK.png Below is the code snippet: < ...

How can jQuery's .append() method be used to replace the text in a <textarea> with a random number?

Simple Explanation: I want to add random numbers to an existing element on the page without affecting it. Every time the page loads, a new random number should be added. The initial problem: While I can successfully append text within an element, I am str ...

Transforming the style of a particular element within React using Array().fill().map's method

Looking for a way to dynamically change the color of an array in React + styled jsx? Let's say you want to change the color when the number of elements in the array is a multiple of 4 (e.g. the index is 4, 8, etc.) Is there a clever solution to achi ...

Embed JavaScript code in the head section of the webpage to guarantee its presence even following a page refresh

We recently obtained an innovative Enterprise Talent Management Solution that is cloud-based. One standout feature allows users to incorporate HTML Widgets with scripts on the primary Welcome Page. The customization options for the Welcome Page UI are qui ...

Tips on how to dynamically allocate an id value to a jQuery function that retrieves the backgroundImage URL

I have a div with a background image and I am using a jQuery function to retrieve the URL of the background image. var name=image; var url=$("#"+name+"").css("background-image"); console.log(url); <script src="https://cdnjs.cloudflare.com/aj ...

Dynamic page changes can be achieved by using JavaScript within HTML, even when the input is

When I click the register button and the input fields appear, the problem arises. When I fill in the fields and then the code jumps to the function $ (document) .on ("click", "#register_in", function (), all $().val(), it results in all values being undefi ...

Numerous toggles available for the mobile version

Hey there, I need some help! I have a footer navigation on my desktop website with 3 Ul elements. I want to turn each Ul into a toggle for the mobile version. Can anyone assist me with this? Thanks in advance! <footer class="footer"> <d ...

Having trouble submitting a FORM remotely on Rails 3.0.3?

I am currently working with Rails 3.0.3 and using jQuery ujs for my project. My goal is to send a form remotely. The view template mains/index.html.erb where the form is located appears like this: ... <%= form_tag :remote => true, :controller => ...

The astonishing font-icon animation feature is exclusively functional on code-pen

I have a problem with a font-icon animation code. When I run it on my local server, the animation doesn't work. It only works on http://codepen.io/TimPietrusky/pen/ELuiG I even tried running it on http://jsfiddle.net/qjo7cf3j/ @import url(http: ...

What is the process for storing data attributes in a database?

I am in the process of developing a website and I have a requirement to store certain variables from HTML in a database. The main goal is to save the paragraphs of text that users select and display them when the user revisits the page (similar to medium.c ...

How can I use jquery's data-dismiss to clear a selected file in Bootstrap?

My image uploader div includes a sub-div to display the chosen file and an <a> element that I aim to delete using jQuery. Has anyone successfully achieved this? I tried binding a click event to the <a>, but it didn't work, possibly due to ...

Randomly Fading Database Elements In and Out

In my current personal project, users are asked to submit statements that are then added to a MongoDB collection. This collection currently contains 50 statements, and I'd like these statements to appear on the webpage in a random fading in and out ef ...