Display or conceal objects within a 3D model with an HTML checkbox

I have utilized JavaScript, CSS, and Three.js to create a 3D model.

The project comprises a total of 5 JS files, 1 CSS file, and 1 HTML file.

Here is an overview of the model:

[]

Showers have been incorporated for each cubicle, which should only be visible when the user selects the checkbox corresponding to a specific cubicle.

For example, if the user ticks the 'cubicle 1 checkbox', the shower should appear in cubicle 1.

Below is a relevant segment of code from the responsible JavaScript file:


        function createPartition() {
            // Code snippet here...
        }
        
        // Additional section of code related to adding showers
        shower = new THREE.Mesh(new THREE.BoxGeometry(0.1, 0.11, 0.45), wallMaterial);
        showerhead = new THREE.Mesh(new THREE.BoxGeometry(0.1, 0.1, -0.04), wallMaterial);

        partitionLeft.add(shower);
        partitionLeft.add(showerhead);
        
        // Positioning of elements
        shower.position.set(0.4, 0.5, -1.312);
        showerhead.position.set(0.4, 0.4, -1.112);
    

The checkboxes' values are defined in the index.html file:


        <input type="checkbox" name="cube1" value="cube1"> Cubicle 1 <br>
        <input type="checkbox" name="cube2" value="cube2" checked> Cubicle 2 <br>
    

Does anyone have any suggestions on how to display the 'shower' when a specific checkbox is selected by the user?

Answer №1

To conceal a shower using only JavaScript, you can start by assigning a class to the shower element and setting its display property to none in your CSS. Make sure each of your shower heads is assigned an ID as well.

Your CSS code would resemble the following:

#showerHead1{
     display:none;
}
.displayShower{
     display:block;
}

Next, create an if statement to check if either checkbox for cube1 or cube 2 is selected, then run:

document.getElementById("showerHead1").className = "displayShower";

This line of code will override the default class for showerHead1 specified in the CSS file.

If you need to remove the class later on, simply use document.getElementById("showerHead1").classList.remove("displayShower");

For further information, consult these resources:

Adding a class: https://www.w3schools.com/jsref/prop_html_classname.asp

Removing a class: https://www.w3schools.com/howto/howto_js_remove_class.asp

Answer №2

When incorporating JavaScript into your code, consider adding an onclick event to the button along with an external function to easily add or remove a specific mesh.

I personally tested this method and found success with it.

I hope you find this solution helpful as well.

Answer №3

Here's a basic idea of how you might approach this:

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 3, 5);
camera.lookAt(scene.position);
let renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

function createCube(id, color, position, isVisible) {
  let cube = new THREE.Mesh(new THREE.BoxGeometry(2, 3, 2), new THREE.MeshBasicMaterial({
    color: color,
    wireframe: true
  }));
  cube.position.copy(position);
  cube.visible = isVisible;
  scene.add(cube);

  let checkboxId = "cube" + id;
  let checkbox = document.createElement("INPUT");
  checkbox.setAttribute("type", "checkbox");
  checkbox.checked = isVisible;
  checkbox.id = checkboxId;
  checkbox.addEventListener("click", function() {
    cube.visible = !cube.visible;
  });

  chbxContainer.appendChild(checkbox);
}

createCube("1", "red", new THREE.Vector3(-2, 0, 0), true);
createCube("2", "blue", new THREE.Vector3(2, 0, 0), false);

animate();

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}

#chbxContainer {
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/93/three.min.js"></script>
<div id="chbxContainer"></div>

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 image is experiencing difficulty loading from the Express static directory

Having some trouble with image loading... I've noticed that images are loading fine from the local folder, but not from the uploads folder which is set to be static. I've been attempting to upload a file from the browser. The upload and save pr ...

Exploring the world of Bootstrap Twitter 3.0 alongside the wonders of Knockout

When utilizing Twitter Bootstrap, the validation classes like has-error or has-warning must be added to the wrapping form-group element to style both the input and its label. However, Knockout-Validation directly adds the class to the input element itself. ...

Experiencing difficulty with loading elements into their respective containers

My goal is to limit the number of alert elements loaded in each .content container to a maximum of 9, but currently I am grouping every 10 items together and discarding any remaining items! For instance, if a random value is 8, then no content will be dis ...

Creating flexible items with a 1:1 ratio and ensuring that the padding on the left and right of the flex container remains consistent

Whenever I adjust the size of the window, https://i.sstatic.net/Fm3d1.png the flex-container ends up with uneven padding on the left and right, which is less than ideal. So, I am looking for a way to allow the flex-item to resize when the window size c ...

ESLint is parsing through alternative configurations

My .eslintrc file is very simple: { "extends": [ "twilio" ] } However, when I run eslint, I encounter this error message: The config "standard" was referenced from the config file in "/Users/MyAccount/Projects/my-sample-app/node_modules/cipher ...

Use jQuery to extract data from the URL instead of relying on PHP

http://h3gsat.altervista.org/DettagliCompleto.php?id=4567 I attempted to extract the id parameter without success. I am attempting to accomplish this using JavaScript (jQuery) instead of PHP, but I am unsure of how to proceed. ...

Inaccurate Guild Member Filtering

Recently, I've been working on creating a unique member counter for my server. The goal is to accurately count the total number of members in the server, excluding bots, and counting only bots as well. However, when I attempt to display these counts i ...

JSON objects not loading properly in Bootstrap table

I am facing an issue where my ajax script successfully sends JSON objects to the browser, but the table fails to load the JSON object. Here is my Ajax script: $.ajax({ type : "POST", url : "getLabels.jsp", data : "mail ...

JavaScript functions smoothly on Google Chrome but is restricted on Internet Explorer

Experimenting with the code found on this website to conduct some testing. The javascript functions smoothly in Google Chrome and Firefox, but encounters issues in IE. Interestingly, when I run the html file in IE locally, it does work, but a warning pops ...

Having trouble retrieving information using JSON from openweather.com

Currently, I am facing an issue while attempting to retrieve weather information from the openweather.com API using geo-location (latitude and longitude) data. Despite my efforts, I cannot seem to figure out why the data is not being retrieved successfully ...

Firebase Error: Trying to access properties of null object (indexOf)

Whenever I try to console.log(docSnap), a Firebase error shows up as seen in the image below. Despite attempting various solutions, none have proved effective. https://i.sstatic.net/9R4vE.png useEffect(() => { if (folderId === null) { ...

What could be causing the issue of req.body being undefined within the destination function of Multer's diskStorage?

I'm currently utilizing Multer for managing file uploads within my Express.js application. However, I've encountered an issue when attempting to access the req.body values in the destination function of Multer's diskStorage option – it con ...

What is the method for providing a date format choice in JSON?

I am encountering an issue in my PHP script where I use JSON to pass parameters. When I pass the date as "09-09-2015", it functions correctly. However, when I try to pass the date as $date, it does not work. How can I resolve this problem? $item1 = "test ...

The ng-model in Angular is unable to capture the initial input value on load

I am currently using a window onload script to obtain longitude and latitude data and pass them to hidden input values. $(function() { window.onload = getLocation; var geo = navigator.geolocation; function getLocation() { if (geo) { geo ...

Tips for guiding users to a different page based on whether a linkid is associated with a specific Cat

I created this script, but I am facing an issue with the redirect. Can someone please assist me as soon as possible? <?php include('config.php'); $number = intval($_POST['catid']); $query = mysql_query("SELECT * FROM sound ...

Sorting Columns in PrimeVue DataTable by Date and Time

I am using a PrimeVue DataTable () with the following structure: <DataTable :rows = "5" :value = "apiItems" > <Column v-for="data in columns" :field="data.field" :header="data.header&q ...

What could be causing the readTextFile function to return undefined?

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; function readFile(file) { let fileContents = new XMLHttpRequest(); fileContents.open("GET", file, false); fileContents.onreadystatechange = function () { ...

Utilizing AJAX to integrate the Google Maps Direction API

Currently, I am developing a small website that utilizes the Google Maps API and AJAX to load directions based on selected locations from a dropdown menu. The database stores latitude and longitude coordinates of various locations, which are retrieved via ...

Utilizing Kendo UI DateTimePicker to transfer chosen date to moment.js

Currently, I am working with a Kendo UI DateTimePicker that provides the selected date in the following format: Thu Dec 15 2016 23:23:30 GMT-0500 My objective is to pass this date into moment.js for extracting the day information like so: var momentDate ...

Is there an alternative solution to the issue of the jQuery resize() event not triggering when an input is

Despite the fact that the jQuery event resize() should trigger when the width of an input box changes, it seems to be malfunctioning. As per the jQuery API documentation, the resize event is supposed to go to the (window) handler. So my query here is, what ...