How come my div doesn't stick together with the other div while moving?

I am trying to figure out how to make the blue "shield" div cover the red "button" div after 3 clicks successfully. It seems like no matter what I do, the positioning is always off. I've played around with the randomplace variable, but nothing seems to be working. Can anyone offer some guidance?

<div id="shield"></div>
<div id="button" onclick="buttonClick()">
   <div id="message"></div>
</div>
<style>
    #button {height:200px; width:200px; background-color:red;position:absolute;top:50%;left:50%;border-radius:50%;}
    #button:active{transform:scale(0.9,0.9);}
    #message{position:relative;top:50%;left:35%;}
    #shield{height:200px;width:200px;background-color:blue;visibility:hidden;position:absolute;top:50%;left:50%;}
</style>
<script>
    var clickCount = 0;
    var shieldDiv = document.getElementById("shield");
    function randomLocation() {
        var randomlyPlace = function(element){
            element.style.position = "absolute";
            element.style.top = Math.floor(Math.random()*document.body.clientHeight);
            element.style.left = Math.floor(Math.random()*document.body.clientWidth);
        };

        randomlyPlace(document.getElementById('shield'));
        randomlyPlace(document.getElementById('button'));

    }
    function buttonClick() { 
        if (clickCount === 0) {
            document.getElementById("message").innerHTML = "Hey stop it!";
            clickCount++;
            randomLocation();
        }
        else if (clickCount === 1) {
            document.getElementById("message").innerHTML = "I said stop!";
            clickCount++;
            randomLocation();

        }
        else if (clickCount === 2){

            document.getElementById("message").innerHTML = "Ha! Now you can't get me!";
            shieldDiv.style.visibility = "visible";
            clickCount++
        }
        else if (clickCount === 3) {
            shieldDiv.style.visibility = "hidden";
            document.getElementById("message").innerHTML = "How did you get me!?!";
            clickCount++;
        }
    }
</script>

Answer №1

Suggestion:

  • For the style selector #shield, consider adding the z-index property to ensure the shield element is brought to the front
    • This method effectively blocks the red button element

Insight:

  • I have incorporated transparency to allow the red button to be visible against the background
    • Feel free to remove the property opacity: 0.26; if it does not align with your specific requirements
  • To enhance code readability, I have streamlined certain sections, particularly within the randomLocation() function
    • This modification eliminates unnecessary code segments that were present solely for this purpose
  • A reset button has been added to facilitate quick repetitive tests

Check out this interactive example, which is based on your provided code:

var clicknum = 0;
var btn = document.getElementById('button');
var msg = document.getElementById("message");
var shield = document.getElementById("shield");

function randomLocation() {
    var randomTop = Math.floor(Math.random() * document.body.clientHeight) + 'px';
    var randomLeft = Math.floor(Math.random() * document.body.clientWidth) + 'px';
    btn.style.top = shield.style.top = randomTop;
    btn.style.left = shield.style.left = randomLeft;
}

function buttonMsg() {
  if (clicknum === 0) {
    msg.innerHTML = "Hey stop it!";
    clicknum++;
    randomLocation();
  } else if (clicknum === 1) {
    msg.innerHTML = "I said stop!";
    clicknum++;
    randomLocation();
  } else if (clicknum === 2) {
    msg.innerHTML = "Ha! Now you can't get me!";
    msg.style.left = "10%";
    shield.style.visibility = "visible";
    clicknum++
  } else if (clicknum === 3) {
    shield.style.visibility = "hidden";
    msg.innerHTML = "How did you get me!?!";
    clicknum++;
  }
}

function reset() {
  clicknum = 0;
  msg.innerHTML = "";
  shield.style.visibility = "hidden";
  btn.style.top = "50%";
  btn.style.left = "50%";
  msg.style.left = "26%";
}
#button {
  height: 200px;
  width: 200px;
  background-color: red;
  position: absolute;
  top: 50%;
  left: 50%;
  border-radius: 50%;
}

#button:active {
  transform: scale(0.9, 0.9);
}

#message {
  position: relative;
  top: 50%;
  left: 30%;
}

#shield {
  height: 200px;
  width: 200px;
  background-color: blue;
  visibility: hidden;
  position: absolute;
  top: 50%;
  left: 50%;
  /*add z-index to bring to front the element*/
  z-index: 9999;
  /*opacity layer to see the red button*/
  opacity: 0.26;
}
<div id="shield"></div>
<div id="button" onclick="buttonMsg();">
  <div id="message"></div>
</div>

<button type="button" onclick="reset();">Reset</button>

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

The optimal approach for AngularJS services and promises

I have a unique setup in my AngularJS application where I utilize services to make API calls using $http and handle promises in my controllers. Here's an example of my current approach: app.service('Blog', function($http, $q) { var deferr ...

Creating objects with variable-dependent values in node.js

I'm currently working on creating a user database in an object to assign values to each user, but I'm struggling to find a way to accomplish this. I attempted using var data = {} and then eval(`data.user_${user} = value`), however, it only write ...

I am looking to create a feature for my table that adjusts its color scheme based on whether the number is odd or even

My current code is designed to change the background color of td elements for odd and even rows. However, when a new high score is entered, a new td is added but it does not get colored automatically as intended. I am facing an issue where the code is not ...

Is there a way for me to group together shapes that are created randomly by a function? (CMU CS Academy)

Working within the confines of CMU CS Academy's Sandbox, I've developed a function that generates rectangles with random sizes, colors, and positions: # List of available colors app.colors = ['crimson', 'gold', 'dodgerBlu ...

Difficulty altering value in dropdown using onChange function - Material-UI Select in React app

Having trouble updating dropdown values with MUI's Select component. The value doesn't change when I use the onChange handler, it always stays the same even after selecting a new item from the dropdown. I made a functional example on CodeSanbox. ...

Sails.js seems to be malfunctioning, as it does not seem to be recognizing the term 'sails'

It seems like I'm encountering an issue with the 'sails' command not being recognized on my Windows 10 system. Despite following all the installation steps, including globally installing Sails.js through npm and ensuring Node is installed, I ...

Encountering Server Error 500 while trying to deploy NodeJS Express application on GCP App Engine

My goal is to deploy a NodeJS app on gcloud that hosts my express api. Whenever I run npm start locally, I receive the following message: >npm start > [email protected] start E:\My_Project\My_API > node index.js Running API on por ...

Understanding the reasons behind 'undefined' res.body in Express

Why does the response body show as undefined in Express? How can I access the response body properly? Is something going wrong here? import {createProxyMiddleware} from 'http-proxy-middleware' import bodyParser from 'body-parser' impor ...

Enhance jQuery dataTable with live updates from Firestore querySnapshot

Currently, I have implemented jQuery dataTable in my project to display data from Firestore. While everything seems to be working fine, an alert keeps popping up in the browser whenever there is an update in the Firestore data: DataTables warning: table i ...

What is the best way to utilize Rselenium's findElement() function in order to target an xpath based on its text content

Despite researching similar questions on stack overflow, I have not been able to make my code work. Here is the initial code I am working with: library(RSelenium) library(rvest) remote_driver <- RSelenium::remoteDriver( remoteServerAddr = "local ...

Adjusting the height of a textarea with javascript

I am trying to reset the contents and height of an auto resizing textarea element. My attempts so far include: document.getElementById('textarea').value = ''; As well as: document.getElementById('textarea').attribute(&apos ...

How can you correctly include a link to a plain text sitemap file in an HTML document?

Could this code effectively inform Google to index my sitemap (or acknowledge its presence)? <link rel="sitemap" href="./sitemap.txt" type="text/plain" title="Sitemap" /> Google's guidelines allow plain t ...

Top methods for integrating custom divs into your WordPress site using PHP

As someone who is new to wordpress, I have a solid understanding of php, html, css and javascript. I am interested in integrating a custom font resizer into my wordpress site similar to the example shown below: https://i.stack.imgur.com/FwoIJ.jpg What w ...

What could be causing this div to shift positions when the browser window is resized?

When resizing the browser, I'm having trouble keeping the div boxes in place. The bottom-right lower div (vd-grid-sub-box) keeps shifting away when I slightly decrease the browser size. Additionally, vd-grid-right-col overlaps with the banner if the s ...

Tips on adjusting video to the screen size

I am looking to create a fullscreen video for my webpage. I originally used an image as a cover, but now I want to switch to using a video. You can check out my old code on this link. Below is my new video code: <div class="embed-responsive embed-resp ...

Using data-ng-repeat with various elements in Angular

Within the Angular controller, there is a variable that contains the following: $scope.items = [ { title: 'x', type: 'x'}, { title: 'y', type: 'y'} ]; Currently, there are only 2 items in the array, but there w ...

Performing a POST request using XMLHttpRequest with parameters in an asp.net environment

I am working on utilizing a javascript XMLHttpRequest object to send a post request to my action method. Here is my current setup: xmlhttp.open('POST', '../Employees1/HandleFileUpload', true); My action method does not currently take ...

Leveraging AngularJS $promise in conjunction with NgResource

As I delve into the world of AngularJS, I have encountered promises which have proven to be quite beneficial in my learning journey so far. Now, I am eager to explore the optional library resource.js in AngularJS. However, I stumbled upon examples that lef ...

Having trouble changing the query string in the URL with Angular 4?

My search form includes various filters such as text inputs, checkboxes, and radio buttons. Whenever the user interacts with these filters, the query string in the URL needs to be updated. Consider the following scenario: http://example.com/search?myFilt ...

Flowtype: Utilizing type hints for class-based higher order component

I am currently working on typehinting a higher-order component (HOC) that adds a specific prop to a passed Component. The code snippet looks like this: // @flow import React, { Component } from 'react'; import type { ComponentType } from 'r ...