The text appears choppy as the javascript is in the process of loading

Upon integrating a basic javascript function into my website to request data from another source, I noticed that the text in the header div suddenly shifts left and then centers itself while the site is loading. This strange movement occurs every time the browser is refreshed.

I suspect that the issue may be related to my div layout or CSS styling. Although I acknowledge that my code is not flawless, it's unclear whether this specific problem stems from it or persists despite it.

Any suggestions on how to resolve this?

body {
  font-family: 'Roboto', sans-serif;
  max-width: 1000px;
  margin: 0 auto;
  padding: 15px;
}

#hello {
  display: inline-block;
  text-align: center;
}

#logo {
  font-weight: 900;
  font-size: 2em;
  margin-bottom: 15px;
}

#output {
  font-family: 'Roboto';
  font-size: 40px;
  font-weight: 900;
  display: block;
}
<html>

<head>
  <link type="text/css" rel="stylesheet" href="/myip-jerktest.css">
</head>

<body>
  <div id="hello">
    <div id="logo">
      Text Logo Here
    </div>

    <span id="output">
<script>
function getIP(json) {
document.write(json.ip);
}
</script>

<script src="https://api.ipify.org?format=jsonp&callback=getIP">
</script>
</span>

    <div style="width:400px;height:45px">
    </div>
  </div>

</body>

</html>

Answer №1

You can transfer the data to the designated div for output, utilizing this code snippet:

function getIP(json) {
  document.querySelector('#output').innerHTML=(json.ip);
}

body {
  font-family: 'Roboto', sans-serif;
  max-width: 1000px;
  margin: 0 auto;
  padding: 15px;
}

#hello {
  display: inline-block;
  text-align: center;
}

#logo {
  font-weight: 900;
  font-size: 2em;
  margin-bottom: 15px;
}

#output {
  font-family: 'Roboto';
  font-size: 40px;
  font-weight: 900;
  display: block;
}
<html>

<head>
  
</head>

<body>
  <div id="hello">
    <div id="logo">
      Text Logo Here
    </div>

    <span id="output">
      
    </span>

    <div style="width:400px;height:45px">
    </div>
  </div>
      <script>
        function getIP(json) {
          document.querySelector('#output').innerHTML = (json.ip);
        }
      </script>

      <script src="https://api.ipify.org?format=jsonp&callback=getIP">
      </script>
</body>

</html>

The script has been relocated to the end of the body. Please test again.

Answer №2

#greetings {
    display: block; // or leave it empty since divs are by default block-level elements
    text-align: center;
}

Instead of writing the IP address directly, consider appending it within a paragraph tag. Currently, it is being displayed within a span element which is inline.
If you wish to center the span element, you will need to apply CSS styles to make it take up the full width and align it to the center.

Answer №3

Instead of rewriting the HTML document using the write method, you can simply append a new DOM element to the body of the document.

In addition, it is recommended to utilize an XMLHttpRequest request object to fetch the JSON data efficiently.

loadJson('https://cors-anywhere.herokuapp.com/https://api.ipify.org?format=json', getIP);

function getIP(json) {
  let el = document.createElement('DIV');
  el.innerHTML = json.ip;
  document.body.appendChild(el);
}

function loadJson(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'json';
  xhr.onload = (e) => callback(xhr.response);
  xhr.open('GET', url);
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.send();
}
body {
  font-family: 'Roboto', sans-serif;
  max-width: 1000px;
  margin: 0 auto;
  padding: 15px;
}

#hello {
  display: inline-block;
  text-align: center;
}

#logo {
  font-weight: 900;
  font-size: 2em;
  margin-bottom: 15px;
}

#output {
  font-family: 'Roboto';
  font-size: 40px;
  font-weight: 900;
  display: block;
}
<div id="hello">
  <div id="logo">Text Logo Here</div>
  <span id="output"></span>
  <div style="width:400px;height:45px"></div>
</div>

Answer №4

utilize

document.getElementById().innerHTML

Example

body {
  font-family: 'Roboto', sans-serif;
  max-width: 1000px;
  margin: 0 auto;
  padding: 15px;
}

#hello {
  display: inline-block;
  text-align: center;
}

#logo {
  font-weight: 900;
  font-size: 2em;
  margin-bottom: 15px;
}

#output {
  font-family: 'Roboto';
  font-size: 40px;
  font-weight: 900;
  display: block;
}
<html>
<head>
  <link type="text/css" rel="stylesheet" href="/myip-jerktest.css">
</head>
<body>
  <div id="hello">
    <div id="logo">
      Text Logo Here
    </div>
    <span id="output">
   </span>
    <div style="width:400px;height:45px">
    </div>
  </div>
  <script>
    function getIP(json) {
      document.getElementById('output').innerHTML = json.ip;
    }
  </script>
  <script src="https://api.ipify.org?format=jsonp&callback=getIP">
  </script>
</body>
</html>

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

Please ensure there is space reserved for the header above the content

Currently, I am working on creating a webpage with a unique banner design. My goal is for the content to scroll from the bottom and remain fixed directly under the upper portion of the banner. Initially, my idea was to have the content box take up the siz ...

What advantages does JWT have over Firebase that make it the preferred choice?

In our authentication systems, we have the option to verify a user through Firebase or by their stored email in the database. Despite having these methods of verification, why do we incorporate JWT (json web token) into our processes? What distinct advan ...

What is the best way to access the element before and after a specific element in an array using JavaScript?

I need to create a function that accepts a string input, searches for its match in an array, and then returns the previous and next elements in the array. const array = [ "11111", "22222", "343245", "5455", "34999", "34 ...

How to style a div's height responsively behind a circle using CSS

Can a CSS pattern be created with responsive design, ensuring that the background line is always in the correct position and height regardless of window size? https://i.sstatic.net/27Tf2.jpg ...

In order to successfully utilize Node.js, Async.js, and Listeners, one must ensure

Here is the log output from the code below, I am unsure why it is throwing an error. It seems that the numbers at the end of each line represent line number:char number. I will highlight some important line numbers within the code. Having trouble with t ...

Using window.open in Google Chrome results in multiple tabs being opened instead of just one

I have a dynamic input field with a search button. Initially, only one tab is opened when I click the button. But after saving and clicking it again, multiple tabs open for the same URL. The number of tabs is equal to the number of dynamic input fields cre ...

Mastering the Art of Aligning Avatars: Effortless Right Alignment

Here's the updated version of the navigation bar: <nav class="navbar navbar-expand-md navbar-dark bg-dark static-top"> <button class="navbar-toggler" type="button" data-toggle="collapse"> ...

Tips for integrating CSS keyframes in MUI v5 (using emotion)

Hey there! I'm currently working on adding some spinning text, similar to a carousel, using keyframes in my React app. The setup involves MUI v5 with @emotion. Basically, I want a "box" element to show different words every few seconds with a rotating ...

Troubleshooting the issue of AngularJS ui view not auto-scrolling as

Having an issue with Angular's ui-router. When I click on a new view, the page doesn't start at the top but where it was previously. I followed advice to set autoscroll to true in my ui-view, but it's still not working as expected. Uncertain ...

What could be causing AJAX to consistently return identical data to the callback function when distinct objects are supplied as arguments?

I am attempting to make two separate calls to an MVC controller. The first call returns a series of data, while the second call returns a partial view. When I check in Firebug, both calls show "success" status. I am trying to utilize a callback function t ...

Utilizing inline-block for styling code blocks

I'm attempting to format two blocks with varying lengths using inline-block, but block-1 is getting aligned with the length of block-2. I need to keep the height of block-1 at 100px. Check out this jsfiddle for reference: http://jsfiddle.net/CGHZ5/5 ...

Tips for sending HTML code via query string

Currently, I am experiencing a challenge with passing HTML code using QueryString while utilizing the Ajax method to submit comments on my website. This issue arises when I write a post containing code like: "Hi everybody<br />What's up." Inst ...

Adding numerous values to a single key in a JSON object

I am dealing with an array that looks like electronics = ["radio","Tv"] My goal is to create an object similar to { "Ids":"radio:Tv", "type":"electronics" } Any suggestions on how I can accomplish this? Thank you in advance ...

Where is the best place for my function to reside: /mixins or /plugins directory?

Suppose I am utilizing an external package like vue-js-modal and have imported it in the file /plugins/vue-js-modal.js: import Vue from 'vue' import VModal from 'vue-js-modal' Vue.use(VModal) Imagine I have a function that utilizes vu ...

Can I place an anchor tag around the circle element within an SVG element?

Trying to turn an svg circle into a link hasn't been successful. Here's the code that didn't work. <svg height="100" width="100"> <g> <a href="http://www.example.com" target="_blank"> <circle cx= ...

Issues with vue-moment.js in Vue

I'm struggling with incorporating vue-moment or moment.js into a .vue file to work with dates. I want to be able to manipulate a date in the Vue method to calculate the timespan between a past and current time, updating it dynamically. After searching ...

Issue of Vue not resolving Ionic back button component

I'm having trouble figuring out why Vue is giving me a warning and the back button isn't functioning as expected: runtime-core.esm-bundler.js?5c40:38 [Vue warn]: Failed to resolve component: ion-back-button at <TheHeader titulo="Home&q ...

Error Encountered: Internet Explorer 11 Runtime Issue

Recently, I encountered an issue with my code that had been working perfectly fine in IE7 and IE8, but started giving me a runtime error in IE11. The error message stated: "JavaScript runtime error: 'SelectAllCheckboxes' is undefined" Below is t ...

The function toDataURL() in Canvas is storing images in low resolution

I created a unique polygonal background generator using HTML5 canvas which can be found at the following link: http://codepen.io/rfalor/pen/LhinJ Here is the important part of the code: var canvas = document.getElementById("canvas"); var ctx = c ...

"We encountered an error with the external script while trying to load file content using jQuery's ajax function. It

//C.php <script type="text/javascript"> $(document).ready(function(e) { $('div').load("D.php"); }); </script> <div></div> //D.php <script type="text/javascript" src="D.js"></script> //D.js console.log(45 ...