-2

I currently have a page on my site that when you go to, it forwards you to a random page on my site. Right now I am trying to shrink that list if the user is viewing it on mobile. I am having trouble figure this out. Right now I have made two different onLoad functions in the script section, and media queries that remove the html that loads it based on screen size.

<html>
<head>
<script type="text/javascript">
<!--
// Create an array of the links to choose from:
var links = new Array();
links[0] = "spinguy.html";
links[1] = "hardware.html";
links[2] = "flappymatt.html";
links[3] = "spinzone.html";
links[4] = "shlink.html";
links[5] = "goop.html";
links[6] = "spinzone.html";
links[7] = "index1.html";
links[8] = "ghoul.html";
links[9] = "grandma.html";
function openLink() {
  // Chooses a random link:
  var i = Math.floor(Math.random() * links.length);
  // Directs the browser to the chosen target:
  parent.location = links[i];
  return false;
}

<!--
// Create an array of the links to choose from:
var links = new Array();
links[0] = "spinguy.html";
links[1] = "hardware.html";
links[2] = "flappymatt.html";
links[3] = "shlink.html";
links[4] = "ghoul.html";
links[5] = "grandma.html";
function openPhoneLink() {
  // Chooses a random link:
  var i = Math.floor(Math.random() * links.length);
  // Directs the browser to the chosen target:
  parent.location = links[i];
  return false;
}
//-->
</script>

<style>

.phone{
        display: none;
    }
  @media only screen and (max-width: 800px) {
    .computer{
        display: none;
    }
    .phone{
        display: inline;
    }
}
  @media only screen and (max-width: 400px) {
    .computer{
        display: none;
    }
.phone{
        display: inline;
    }
}
</style>

</head>
<body>
<div class="computer" onload="openLink();"></div>
<div class="phone" onload="openPhoneLink();"></div>
</body>
</html>

2 Answers2

0

A few things.

  1. divs don't have an onload event -- this honor is reserved for the body. As such, I moved your onload call to the body tag. <body onload="openLink()">. Check this out.

  2. display: none; doesn't keep an element from loading, it just keeps it from appearing on the page.

  3. You don't even need to use divs for this. If you look at how I have re-written what you are trying to do, you'll see that there aren't any divs on the page. I simply call the function onload and replace the location within the openLink() function.

  4. Use window.location.href to change a page's URL. StackOverflow question.

  5. You don't need to return false at the end of JavaScript functions. They just return to the program flow when they end. (But if you did call them from something that expected a return value and did not have one, you would get undefined.)

  6. I didn't update openLink() to choose from a different array based on the size, but you should use something like let windowWidth = window.innerHeight; and use an if statement depending on the value. Also, take a look at some better ways to use and populate arrays in JavaScript.

    <head>
        <script type="text/javascript">
    
            //get size of window using window.innerWidth and make the link array according to the value
            // Create an array of the links to choose from:
            function openLink() {
                var links = new Array();
                links[0] = "spinguy.html";
                links[1] = "hardware.html";
                links[2] = "flappymatt.html";
                links[3] = "spinzone.html";
                links[4] = "shlink.html";
                links[5] = "goop.html";
                links[6] = "spinzone.html";
                links[7] = "index1.html";
                links[8] = "ghoul.html";
                links[9] = "grandma.html";
                // Chooses a random link:
                var i = Math.floor(Math.random() * links.length);
                // Directs the browser to the chosen target:
                window.location.href = links[i];
            }
    
        </script>
    
    </head>
    
    <body onload="openLink()"></body>
    
    </html>
    
Katie.Sun
  • 711
  • 3
  • 15
0

First, your onload attributes will not work because it is only a valid attribute on a subset of HTML elements, namely:

  • <body>, <iframe>, <img>, <input>, <link>, <script>, <style>

This is because those elements have some sort of async loading associated with them. Check this w3schools.com page for reference.

I assume based on your description that you intended these onload events to occur on the <body> because it has the distinct behavior "to execute a script once a web page has completely loaded all content".

This is okay, because you don't need to separate functions for openLink() and openPhoneLink(), and these can be collapsed into one function for simplicity.

You can avoid the wonkiness of the @media CSS queries as Javascript has the ability to determine the width and height of your viewport anyway.

  • window.screen.width - device width
  • window.screen.height - device height

If you want to get real fancy with dimensions and device rules, you can find references like this one which give you a breakdown of what different dimensional variables in Javascript mean.

Now, back to the question at hand...

You can test the device switch by using something like the Chrome Developer Tools and toggling between mobile devices and refreshing the browser. In this case, my 800 pixel check is not good enough to know an iPad is not a computer, but you can put whatever rules you want in here.

I've taken the liberty to give you a more re-usable data structure for your links. I hope this helps you out:

<html>
<head>
<script type="text/javascript">

const Device = {
  COMPUTER: "computer",
  PHONE: "phone"
}

const links = [
  { href: "spinguy.html", computer: true, phone: true, },
  { href: "hardware.html", computer: true, phone: true, },
  { href: "flappymatt.html", computer: true, phone: true, },
  { href: "spinzone.html", computer: true, phone: false, },
  { href: "shlink.html", computer: true, phone: true, },
  { href: "goop.html", computer: true, phone: false, },
  { href: "index1.html", computer: true, phone: false, },
  { href: "ghoul.html", computer: true, phone: true, },
  { href: "grandma.html", computer: true, phone: true, },
]

const randomIndex = (length) => {
  return Math.floor(Math.random() * length)
}

const device = () => {
  // modify as needed to distinguish devices you care about
  return window.screen.width >= 800 ? Device.COMPUTER : Device.PHONE
}

const openRandomLink = () => {
  const deviceKey = device()
  // console.log("deviceKey", deviceKey)
  const validLinks = links.filter(link => link[deviceKey])
  const randomLinkIndex = randomIndex(validLinks.length)
  const randomLink = validLinks[randomLinkIndex].href
  // console.log("randomLink", randomLink)
  window.location.href = randomLink
}

</script>

</head>
<body onload="openRandomLink()">
</body>
</html>
forgo
  • 932
  • 1
  • 7
  • 20
  • I didn't mention it in my post, but @Katie.Sun makes some good points about how you would populate an array. In this case since you know all your data upfront, it's fine to use an array literal, but she is right that you don't need to create an Array and then populate it index-by-index, manually (that's just silly). Also, I forgot to correct the usage of `parent.location` to `window.location.href`, so I've borrowed from their answer and edited that. – forgo Dec 05 '18 at 02:20