Having trouble obtaining the accurate dimensions of a div after it has been created

Here is a notification code that I want to display in the center of the screen. Interestingly, on the first click, it doesn't appear in the middle, but on the second click, it works as expected. It seems like there might be an issue with height and width.
(help without defining css)

var showNotice = function(txt,mode){

 var mode = mode || 0;
 var width = $(window).width();
 var height = $(window).height();
 $("body").append("<span id='notice'>" + txt + "</span>");
 var noticeW = $("body #notice").outerWidth();
 var noticeH = $("body #notice").outerHeight();
 $("body #notice").css({
    "position": "absolute",
    "z-index": "1000",
    "background": "black",
    "color": "white",
    "padding": "20px",
    "cursor": "pointer",
    "border-radius": "8px",
    "box-shadow": "0 0 15px rgba(0,0,0,0.6)",
    "top": (height / 2) - (noticeH / 2) + "px",
    "left": (width / 2) - (noticeW / 2) + "px",
    "display": "none"
 }).fadeIn();

 $(document).on("click", "body #notice", function(){
    $("body #notice").fadeOut(1000, function(){
        $(this).remove();
    });
 });

 if(mode === 0){
    setTimeout(function(){
        $("body #notice").fadeOut(1000, function(){
            $(this).remove();
        });
    },5000);
 }

} // ----- showNotice() -----

Html

<button onclick="showNotice('some text',1)">
 Click
</button>

JSfiddle

Answer №1

One reason for this is that when you're trying to get the #notice, its outerHeight and outerWidth properties may not have been defined yet, along with any other CSS styles. You can solve this issue by following this approach: Check out the DEMO here

var showNotice = function(txt, mode) {
    var mode = mode || 0;
    var width = $(window).width();
    var height = $(window).height();
    $("body").append("<span id='notice'>" + txt + "</span>");
    $("body #notice").css({
        "position": "absolute",
        "z-index": "1000",
        "background": "black",
        "color": "white",
        "padding": "20px",
        "cursor": "pointer",
        "border-radius": "8px",
        "box-shadow": "0 0 15px rgba(0,0,0,0.6)"
    });
    var noticeW = $("body #notice").outerWidth();
    var noticeH = $("body #notice").outerHeight();
    $("body #notice").css({
        "top": (height / 2) - (noticeH / 2) + "px",
        "left": (width / 2) - (noticeW / 2) + "px",
        "display": "none"
    }).fadeIn();

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

Tips on fetching and displaying information by utilizing the .click(function()

I have a single textfield and a show button. After entering some text into the textfield and clicking the button, I want to display all information from the database. What code do I need to achieve this? $(document).ready(function(){ var oTable; $("#show ...

Minimize/Maximize Selection Options (optgroup)

Check out the example plnkr I created: Plnkr I'm curious to know if there's a way to make the bold labels expandable and collapsible. I've been experimenting with different methods, but haven't found a solution that allows me to only d ...

Implementing a jQuery function to activate a click event on an li element

I am trying to trigger a click event on a span tag when it is clicked. A list item (li) is created when the span tag is clicked to create a collection. Below are my span and ul li tags. The li list is added dynamically to the ul when the span is clicked. ...

Verify if the current carousel item is active and contains an attribute with a value of 1

I am currently utilizing the bootstrap carousel component: <div class="carousel-item slide" data-llp-is-question="0"></div> <div class="carousel-item slide" data-llp-is-question="0"></div> <div class="carousel-item slide" data-l ...

It is not possible for me to restore a previously deleted element from the table

<table class="files-table table"> <thead> <th>Filename</th> <th>Type</th> <th>Status</th> <th oncli ...

Tips for ensuring all my onclick event are clickable in iOS browser

Currently, I am developing a web page using HTML5 and JQuery Mobile. I have encountered an issue where the onclick function does not work on iOS device browsers. Is there a way to change all onclick events to be accessible through tapping instead? This wou ...

Verify the validity of the user's input

Using knockout.js and knockout.validation, I have created a book view model with properties for the author's name and book title: function BookViewModel(bookObj) { var self = this; self.AuthorName = ko.observable(bookObj.AuthorName) ...

Parallax Page with a Stylish CSS Navigation Bar

I've been searching for tutorials on parallax effects and I've managed to implement it successfully. However, when I tried adding a navigation bar to the parallax page, the results were not what I expected. Can someone assist me with this? Below ...

Struggling to align elements in a navbar using HTML and CSS?

Currently, I'm in the process of building a simple website and focusing on customizing the navbar. The logo within the navbar is created using font awesome and text, with a larger font size compared to other elements in the navbar. However, I am facin ...

Get rid of all list items inside an unordered list within a div

I am looking for a way to use jQuery to remove all items from a list that is contained within a div. The challenge lies in the fact that the ul element does not have a specific class or id, but the surrounding div does have an id attribute. <div id="m ...

Use HTML accept-charset to specify the character encoding for form fields

Curious if a form field could handle characters with accents like Ś or ý and display them as the raw letter (Ś or ý) instead of "random symbols" like percents upon submission. Is this achievable? ...

What is the best way to collapse a button in asp.net using javascript after setting it to hidden?

I have a scenario where I have 3 buttons in a row on my asp.net page. Using JavaScript, I am setting the middle button (ButtonSR) to invisible. However, I want the button below it to move up and take its place instead of leaving an empty space. ...

Trouble getting the onclick event to function properly with PHP, ajax, and jQuery

I am looking to incorporate an onclick event using PHP to achieve a specific goal. My aim is to utilize ajax to prevent page refreshing and generate buttons upon click events. I am uncertain about merging the div buttons with the ajax outcome. The PHP fi ...

The unpredictable number generator fails to generate the anticipated numbers within a specified range by utilizing input values from the fields

Trying to create a random number within specified boundaries has been more challenging than expected. Although I have a function that works flawlessly under normal circumstances, it seems to give unexpected outputs when the minimum and maximum values are d ...

After all AJAX requests have finished executing

I am facing a challenge with an ajax request where I grab data and split it into an array of variable length. var ajax1 = $.ajax({ url: 'myurl.php', type: "GET", dataType: "jsonp", success: function (data) { //creating a ...

Difficulty comprehending the fallback for JSON.parse in jQuery.parseJSON

Check out the origin of $.parseJSON function (data) { if (typeof data !== "string" || !data) { return null; } // Remove leading/trailing whitespace for compatibility data = jQuery.trim(data); // Try native JSON parser first ...

Vanilla Javascript's alternative to $(document).on

Can someone provide me with the plain vanilla JavaScript code equivalent to the jQuery code below? $(document).on("mousemove touchmove", function(e) { console.log(e.touches[0].pageX); //code }); I understand how to implement this in ...

Troubleshooting incorrect values retrieved with ASP.NET MVC and Jquery's .val() method

<input type="text" id="start" value="example" /> $.get('@Url.Action("StartGet", "Test")' + '?id=' + fisid, function (response) { $("#start").val(response); }); once the value is retrieved var initialValue = ...

How to position Angular Component at the bottom of the page

I have been working on my angular application and recently created a footer component that I want to stay at the bottom of the page like a typical footer. The footer component is included in the default app.component.html file, which makes it visible on th ...

What is the method for delivering tailored information to DataTable's server-side processing without using the DataTable filter input?

In my webpage, there are four input fields that allow users to customize their search for records in the database. The results will be presented in a DataTable located below these input fields: https://i.sstatic.net/Fez9Z.png Below is the JavaScript code ...