JavaScript box creation explained

I've been experimenting with JavaScript to create multiple boxes at the top of my page. While I've successfully created one box, I'm struggling to extend this to have several boxes across the top. This is where I'm currently stuck:

    <html>
  <head>
    <title>Multiple Boxes Display</title>
    <link rel="stylesheet" type="text/css" href="boxes.css">
    <script language="JavaScript">
        el=document.getElementById("box1");
        width=window.innerWidth-50;
        height=window.innerHeight-50;
        el.style.left=width*Math.random();
        el.style.top=height*Math.random();

        el=document.getElementById("box2");
        width=window.innerWidth-50;
        height=window.innerHeight-50;
        el.style.right=width*Math.random();
        el.style.top=height*Math.random();

        el=document.getElementById("box3");
        width=window.innerWidth-50;
        height=window.innerHeight-50;
        el.style.middle=width*Math.random();
        el.style.top=height*Math.random();

    </script>
  </head>
  <body>
    <div id="box1">
      First box 
    </div>

    <div id="box2">
        Second box
    </div>

    <div id="box3">
        Third box
    </div>
  </body>
</html>

To style these boxes, here is the CSS I have:

#box1{
    background-color:orange;
    padding:5px;
    width:50px;
    height:50px;
    position:absolute;
    left=100px;
    top=100px;
}
#box2{
    background-color:blue;
    padding:5px;
    width:50px;
    height:50px;
    position:absolute;
    left=100px;
    top=100px;
}
#box3{
    background-color:green;
    padding:5px;
    width:50px;
    height:50px;
    position:absolute;
    left=100px;
    top=100px;
}

Answer №1

To ensure that the <script> element functions correctly, consider moving it to the end of your code or wrapping it in a DOM ready or onload handler. This will allow getElementById() to locate elements after they have been parsed.

Don't forget to include a unit (such as "px") in the left and top style properties.

Avoid recalculating the width and height for each box, as the same calculations are being repeated unnecessarily. It's also recommended to declare variables using var, although this is not essential for functionality.

Check out this revised version below:

    var el=document.getElementById("box1");
    var width=window.innerWidth-50;
    var height=window.innerHeight-50;
    el.style.left=width*Math.random() + "px";
    el.style.top=height*Math.random() + "px";

    el=document.getElementById("box2");
    el.style.right=width*Math.random() + "px";
    el.style.top=height*Math.random() + "px";

    el=document.getElementById("box3");
    el.style.middle=width*Math.random() + "px";
    el.style.top=height*Math.random() + "px";

See the demo here: http://jsfiddle.net/m3Gg3/

Additionally, ensure that the left and top properties in your CSS use : instead of =.

Answer №2

Understanding your requirements may pose a challenge, could this solution be what you are looking for?

<script>
window.onload = function() {
    var categories = ["Category A", "Category B", "Category C"]
    var width=window.innerWidth-50
    var height=window.innerHeight-50-120
    for (var i = 0; i < categories.length; i++) {
        var element = document.createElement('div')
        console.log(element)
        element.innerHTML = categories[i]
        element.style.position = "absolute"
        element.style.border = "1px solid rgb(0,0,0)"
        element.style.left= (width / categories.length) * i
        element.style.top=0
        element.style.width = width / categories.length
        element.style.height = "120px"
        document.body.appendChild(element);
    }
    for (var i = 0; i < categories.length; i++) {
        var element = document.createElement('div')
        console.log(element)
        element.innerHTML = categories[i]
        element.style.position = "absolute"
        element.style.border = "1px solid rgb(0,0,0)"
        element.style.left=0
        element.style.top=(height / categories.length) * i + 120
        element.style.width = "120px"
        element.style.height = height / categories.length
        document.body.appendChild(element);
    }
}
</script>

Answer №3

    <html>
  <head>
    <title>Colorful Boxes</title>
    <style type="text/css">
#box_group1, #box_group2, #box_group3, #box_group4, #textbook {
    position:absolute;
    left:100px;
    top:100px;      
}
#box1, #box2, #box3, #box10, #box11, #box12 {
    padding:5px;
    width:50px;
    height:50px;
    cursor:pointer;
    float:left;
}
#box4, #box5, #box6, #box7, #box8, #box9 {
    padding:5px;
    width:50px;
    height:50px;
    cursor:pointer;
}   
#box1, #box4, #box7, #box10{
    background-color:orange;
}
#box2, #box5, #box8, #box11 {
    background-color:blue;
}
#box3, #box6, #box9, #box12{
    background-color:green;
}
#box4, #box7 {
    font-family: Arial;
}
#box5, #box8 {
    font-family: Courier;
}
#box6, #box9 {
    font-family: Tahoma;
}   
#textbook {
    padding: 5px;
    background-color:red;
}
    </style>
    <script language="JavaScript">
        width=window.innerWidth;
        height=window.innerHeight;
    function boxes() {  
        document.getElementById("box_group1").style.left=(width-document.getElementById("box_group1").offsetWidth)/2;
        document.getElementById("box_group2").style.top=(height-document.getElementById("box_group2").offsetHeight)/2;
        document.getElementById("box_group3").style.left=width-100-document.getElementById("box_group3").offsetWidth;
        document.getElementById("box_group3").style.top=(height-document.getElementById("box_group3").offsetHeight)/2;
        document.getElementById("box_group4").style.left=(width-document.getElementById("box_group4").offsetWidth)/2;
        document.getElementById("box_group4").style.top=height-100-document.getElementById("box_group4").offsetHeight;  
        document.getElementById("textbook").style.left=(width-document.getElementById("textbook").offsetWidth)/2;
        document.getElementById("textbook").style.top=(height-document.getElementById("textbook").offsetHeight)/2;
    }

    function colorChange(field,group) {
        switch (group) {
            case 1:
                document.getElementById("box2").style.backgroundColor = field.innerText;
                break;
            case 4:
                document.getElementById("box11").style.backgroundColor = field.innerText;
                break;
        }       
    }
    function fontChange(field,group) {
        switch (group) {
            case 2:
                document.getElementById("box5").style.fontFamily = field.innerText;
                break;
            case 3:
                document.getElementById("box8").style.fontFamily = field.innerText;
                break;
        }       
    }       
    </script>
  </head>
  <body onload="boxes()">
    <div id="box_group1">
        <div id="box1" onclick="colorChange(this,1)">
            Orange 
        </div>

        <div id="box2" onclick="colorChange(this,1)">
            Blue
        </div>

        <div id="box3" onclick="colorChange(this,1)">
            Green
        </div>
    </div>
    <div id="box_group2">
        <div id="box4" onclick="fontChange(this,2)">
            Arial 
        </div>

        <div id="box5" onclick="fontChange(this,2)">
            Courier
        </div>

        <div id="box6" onclick="fontChange(this,2)">
            Tahoma
        </div>
    </div>
    <div id="box_group3">
        <div id="box7" onclick="fontChange(this,3)">
            Arial
        </div>

        <div id="box8" onclick="fontChange(this,3)">
            Courier
        </div>

        <div id="box9" onclick="fontChange(this,3)">
            Tahoma
        </div>
    </div>
    <div id="box_group4">
        <div id="box10" onclick="colorChange(this,4)">
            Orange 
        </div>

        <div id="box11" onclick="colorChange(this,4)">
            Blue
        </div>

        <div id="box12" onclick="colorChange(this,4)">
            Green
        </div>
    </div>
    <div id="textbook">Textbook</div>
  </body>
</html>

Answer №4

Give this jQuery solution a try:

Instead of hardcoding IDs, dynamically create boxes in a more efficient way using your code. It's simple when you're making 4 boxes, but what about scaling up to 100 or more? It's best to always prioritize scalability in our work.

HTML :

<div id="mainDiv">

</div>

CSS :

// styling for all divs inside mainDiv 
#mainDiv div{
    padding:5px;
    width:50px;
    height:50px;
    position:absolute;
    left=100px;
    top=100px;  
    float : left;
}

jQuery :

$(document).ready(function(){
    // define color array
    var colorArray = new Array("red", "green", "gray", "blue");
    // loop through desired number of boxes to create
    for(var i = 1; i <= colorArray.length; i++){
        $("#mainDiv").append("<div id=Box" + i + "></div>");
        //set background-color property based on color array
        $("#Box"+ i).css("background-color", colorArray[i-1]);
    }
});

See Demo

Check out a discussion thread on a similar case, and its proposed solution.

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

Having trouble with dynamic path generation for router-link in Vuejs when using a v-for loop?

//main.js import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import HelloWorld from "./components/HelloWorld.vue"; Vue.use(VueRouter); const router = new VueRouter({ routes: [{ path: "/", component: HelloWorld }] } ...

apostrophe cutting off a portion of the input field's value

I am facing an issue with a reloaded input box on a web page that is updated through an ajax call. Whenever the input contains a single quote, the rest of the value gets cut off. How can I resolve this problem? The value assigned to myVal dynamically from ...

What is the best way to enable momentum-based scrolling for the root <html> element in iOS Safari?

We are encountering difficulties in implementing momentum-based scrolling on iOS Safari for the root <html> element. The following CSS snippet yields the desired outcome: html { height: 100%; overflow-y: scroll; } ...

Guide to deleting a user from a list in AngularJS

I created a confirm button to delete a user from the list, but for some reason it's not working. Could someone please review my JavaScript code to see if there are any mistakes? Here is the JavaScript code: $scope.doDelete = function(user) { ...

Preventing line breaks (endline) from PHP variable when passing to JavaScript

Check out my code snippet below: <td onclick="openFile('<?php echo htmlentities ($row['name'])?>',' <?php echo htmlentities ($row['content'])?>')"> <a href="#nf" dat ...

JavaScript fails to execute in Prestashop

Can anyone help me troubleshoot my countdown shipping time code? Here is the script I am using: http://jsfiddle.net/37ox54bk/7/ I am utilizing the HTML box module found here: This is how the code looks: <div id="countdownTimer">0</div> ...

Comparing the use of visibility: hidden with -webkit-transform: translate3d() within a PhoneGap application

Currently, I am creating a hybrid application using PhoneGap. As part of the design, I have several divs (each representing a page) that I toggle between by changing their visibility in CSS using "visibility: hidden" and "visible". However, I recently ca ...

The importance of formatting values in JavaScript

I currently hold the following set of values: var val = "2520,3569,99991,14203,11918"; In addition, my tests are listed in a certain format (see attached screenshot), containing all the test values. From this extensive list, I am only interested in speci ...

Avoid changing the format when sending a JSON string to Node

I am attempting to send JSON data to a Node application using a POST request, which will then be retrieved through a GET request. On the client side, I create a JSON string representing the model and send it to the server: $.post(serverURL, ko.mapping.toJ ...

I'm having issues with my onchange event not triggering. Can't figure out the cause

I'm currently attempting to modify the .innerText property of the first occurrence of a</ode> whenever the selected value of the <code>option equals 1. Despite not encountering any errors in the console and relocating my script within the ...

Revisiting Async Await: A guide to implementing callbacks

I have the following code snippet: const myImage = document.querySelector('img'); const myRequest = new Request('flowers.jpg'); fetch(myRequest).then((response) => { console.log(response.type); // returns basic by default respo ...

Creating a brand new array based on the conditions of an if statement

I have an array of objects and I need to search for objects with a specific property. Once found, I want to create a new array only containing those objects. var firstArray = [...] for (var i = 0; i < firstArray.length; i++) ...

Having difficulty with an API request and retrieving information from it to showcase on the web browser

Struggling to recreate a product details page using an API for the first time. I managed to fetch the data but extracting the necessary information for the browser is proving difficult. YouTube videos haven't been much help. This is my attempt at cal ...

Add the response from the API to a table

Looking to extract data from a public holidays API and present it on a leaflet map through a table in a pop-up. The pop-up is functional, and the data is visible in the console but not appearing in the actual pop-up. The code does not add new rows to the ...

Focus on the original control that triggered a jQuery AJAX POST during a postback event

function pageLoad() { $(".VoteUp").live("click", function () { var Id = $(this).attr("index"); d = JSON.stringify({ "Id": Id }) $.ajax({ type: 'POST', url: '../API ...

AngularJS is capable of dynamically altering the URL based on the specific HTTP method being used, such as

I have implemented Angular factories to connect ajax requests with my web api. Below is an example of how the factory is structured. app.factory('QuestionContainer', ['$resource', function ($resource) { return $resource('http://lo ...

How can I access an object from a JavaScript file within a Laravel blade template?

I am trying to implement the package Sortablejs in my blade file. After installing it with npm, I created a sortable.js file within my assets folder containing the following code: import Sortable from "sortablejs"; This file is compiled into th ...

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...

Best practices for customizing v-calender in vue.js

I'm struggling with styling my calendar using the v-calendar Vue plugin. I want to customize the background of the calendar, but my code doesn't seem to be working. Can someone please help me out? Thank you in advance. HTML <v-calendar ...

What is the best way to extract data from multiple instances of <span> tags and store them in an array?

I am in search of the most effective method for extracting multiple span tags from various spans and organizing them into an array or JSON object for future use. (I'm unsure whether an array or JSON is the optimal choice.) HTML: <span class="car" ...