Home > other >  How to execute some code based on ip address in javascript or jQuery?
How to execute some code based on ip address in javascript or jQuery?

Time:02-07

I am trying to make a premium version of my website and allowing only premium members to view some divs or hide ads, etc. I wanted to do it based on IP addresses. For that I searched the web and found this snippet:

<script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
<script type="text/javascript">
if (userip== 0.0.0.0 || 1.1.1.1) { // More addresses as required. Given addresses are for example only
document. getElementsByClassName('ads-here'). style. display = "none";
}</script>

But as always the above code doesn't work. I tried to do document.write and the output comes perfectly fine. What seems to be the problem here. Please explain.

Note 1: I am still learning JavaScript.

Note 2: The platform of my website is Blogger (Idk if that matters)

CodePudding user response:

Your code, document.getElementsByClassName('ads-here').style.display = "none";, is incorrect because getElementsByClassName returns an HTMLCollection, not an Element. You will have to loop through the result of document.getElementsByClassName('ads-here') and set their style.display to "none". Example:

for (const element of document.getElementsByClassName('ads-here')) {
    element.style.display = "none";
}

CodePudding user response:

Try to use function(). Your src not fully ready, so the userip is null userip == 0.0.0.0 always be false.

<script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
<script type="text/javascript">
    (function() {
       if (userip== 0.0.0.0 || 1.1.1.1) { // More addresses as required. Given addresses are for example only
       document. getElementsByClassName('ads-here'). style. display = "none";
    }
    })();
    </script>

Edit: made it to work. Should first define userip. PS: Ublock Origin blocking l2.io.

<div > dsgdfgadf </div>

<script type="text/javascript">
  var userip;
</script>
<script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
<script type="text/javascript">
   (function() {
  if (userip == '0.0.0.0') {
      document. getElementsByClassName('ads-here')[0].style.display = "none";
    }
      console.log(userip)
   })();
</script>

  •  Tags:  
  • Related