About Math.random();

  • Returns a number between 0-1

  • Make sure that the M in Math.random() is capitalized, smh

Using Math.random() to have a popup appear at a random area of viewport on page load

  • Assigning a variable var randomTop = Math.random() * height; to call out a specific variable to do the math, because Math.random() will assign a number between 0 to 1. At least if we add a multiplier (window.innerHeight/Width) it will multiply that and remain within the viewport (height in this variable is already assigned window.innerHeight.
  • Then using CSS to move box when the page has loaded
const height = window.innerHeight;
const width = window.innerWidth;
 
$(function() {
  /* calling out a specific variable to do the math, because Math.random() will assign a number between 0 to 1. At least if we add a multiplier (window.innerHeight/Width) it will multiply that and remain within the viewport */
  var randomTop = Math.random() * height;
  var randomLeft = Math.random() * width;
 /* changing the positioning of the popup via css */
  $(".popup").css("top", randomTop);
  $(".popup").css("left", randomLeft);
})

https://codepen.io/macaspac/pen/dyjKbbz

This is the snippet I ended up using on my website (this includes the draggable aspect of each popup, and the z-index for every time you click on a pop up so it shows up on top) :

<script
  src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
  integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
  crossorigin="anonymous"></script>
  
<script>
if (window.screen.width > 780) {
$("\#popup-about").draggable();
$("\#popup-paint").draggable();
$("\#popup-contact").draggable();
$("\#popup-img").draggable();
$("\#popup-portrait").draggable();
$("\#popup-anime").draggable();
 
$(".popup").mousedown(function () {
    $(".popup").css("z-index", 0);
    $(this).css("z-index",1);
});
 
var popup = document.querySelectorAll('.popup');
var newq;
let h,w; 
 
function popupPosition(){   
  h = window.innerHeight - 50;
  w = window.innerWidth - 50;
  nh = Math.floor(Math.random() * h);
  nw = Math.floor(Math.random() * w);
  return [nh,nw];  
}
 
popup.forEach(function popup(myclass) {
  var newq = popupPosition();
  $(myclass).css({ 
    top: newq[0], left: newq[1] 
    })
})
 
 
}
</script>