Search code examples
javascripthtmlip-address

Public IP address as variable in JavaScript/HTML


How can I get a public IP address as a; var ip = $("#ip") ?

I hope to achieve is to put a public IP address into a var.

So far I have this:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script>
var yourip = document.getElementsByTagName("body")[0].ip
window.alert("your IP is" + yourip);
</script>
<body>
<span id="ip"></span>
</body>
<script type="text/javascript">
$.getJSON("http://jsonip.com?callback=?", function (response) {
$("#ip").text(response.ip);
});
</script>


Solution

  • Your code is fine all you need is assign value to the variable. To read more about JavaScript Operators.

    var yourip = document.getElementsByTagName("body")[0].ip
    window.alert("your IP before " + yourip);
    $.getJSON("http://jsonip.com?callback=?", function (response) {
    yourip = response.ip;
    $("#ip").text(response.ip);
    window.alert("your IP after " + yourip);
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span id="ip"></span>