What strategies can be utilized to enhance the cleanliness of these functions?

Is there a way to avoid adding new lines of JS code every time I add a new image to the HTML?

$(document).ready(function() {
$('.btn').click(function() {
var bid = $(this).attr('id');
if(bid=="img1" || bid == "img2" || bid == "img3"){
    document.getElementById("img1").style.display = "none";
    document.getElementById("img2").style.display = "none";
    document.getElementById("img3").style.display = "none";
        } else {
            document.getElementById("img4").style.display = "none";
            document.getElementById("img5").style.display = "none";
        }
        document.getElementById(bid).style.display = "block";
    });
});

CSS

.textures {
    background: url("images/room.png") center / cover no-repeat;
    position: static;
    height: 600px;
    width: 800px;
}
div>img {
    display: none;
    position: absolute;
}
[type=radio] {
    position: absolute;
    opacity: 0;
    width: 0;
    height: 0;
}
[type=radio] + img {
    cursor: pointer;
    height: 60px;
    width: 80px
}
[type=radio]:checked + img {
    outline: 2px solid #000;
}

HTML. If a radius input from the categories is clicked, an image from materials will be displayed.

<!--Room materials-->
<div class="textures">
    <div class="wall">
        <img id="img1" src="images/wall/blue.png" /> 
        <img id="img2" src="images/wall/brick.png" /> 
    </div>

    <div class="floor">
        <img id="img3" src="images/floor/cedro.png" /> 
        <img id="img4" src="images/floor/cipres.png" />
    </div>
</div>

<!--Categories-->
<h5>Walls</h5>
<label>
    <input type="radio" class="btn" id="img1" name="test" value="small" />
    <img src="images/thumbnail/wall/blue.png"/>
</label>
<label>
    <input type="radio" class="btn" id="img2" name="test" value="small" />
    <img src="images/thumbnail/wall/brick.png"/> 
</label>

<h5>Floors</h5>
<label>
    <input type="radio" class="btn" id="img3" name="test" value="small" />
    <img src="images/thumbnail/floor/cedro.png"/> 
</label>
<label>
    <input type="radio" class="btn" id="img4" name="test" value="small" />
    <img src="images/thumbnail/floor/cipres.png"/> 
</label>

See an example here.

Similar to what can be achieved here.

Answer №1

It is important to note that having duplicate IDs within a single document goes against proper HTML guidelines. Instead of using duplicate IDs to establish connections between elements, consider utilizing data attributes as an alternative method. By extracting the data attribute, concealing all images, and incorporating the data attribute into a selector, you can achieve the desired functionality:

<input type="radio" class="btn" data-image="img4" name="test" value="small" />
                                ^^^^^^^^^^^^^^^^^
$('.btn').on('change', function() {
  const id = $(this).data('image');
  $('.textures img').hide();
  $('#' + id).show();
});

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

Can the behavior of "flex-end" be emulated in :before and :after pseudo-elements?

I have come across a piece of code that creates a checkbox using the pseudo-elements :before and :after, along with a hidden input to handle the selection logic. The current setup works fine and behaves as expected. However, I am curious if it is possible ...

Adjust the color of the bootstrap navbar upon resizing the screen

Attempting to modify the background color for the navbar menu items on smaller screen sizes. An issue arises in the following scenario: Browser window is resized until hamburger menu appears Hamburger menu is clicked to display menu i ...

Upon loading, make sure to click on the link located within the third <li> tag

I am working with a list (<ul>): <ul class="options_inner"> <li><a data-dk-dropdown-value=".option1"></a></li> <li><a data-dk-dropdown-value=".option2"></a></li> <li><a data- ...

What is the best way to switch between three different menus and ensure that the last selected menu remains open when navigating to a new page

My knowledge of javascript, jquery, and php is pretty much non-existent, unfortunately. I only have a grasp on html and css at the moment. However, I will be starting school to learn these languages in the fall! The issue I am currently facing is creating ...

How come my uvmapped texture is flipping vertically when using iewebgl + threejs?

Currently in the process of developing a 3D viewer for game pads with the aim of customizing the pad using various colors and materials. Initially, I created a simple ".bin .js" loader with sample materials using Threejs r62 to create a visualizer prototy ...

What is the best way to center these icons vertically in my navigation menu using CSS?

My website has a navigation menu with third-party icon libraries (Material/FontAwesome) in use. I am facing an issue where the icons are not aligning vertically with the anchor text. Adjusting the font size of the icon to match the text results in it appe ...

Cookie Setting - Utilizing a jQuery Modal Box for Confirmation Messages

This unique jquery_modal_confirm_dialogue has been perfected through numerous experiments. When our site visitors agree to our Terms of Use, they are automatically directed to the product page products.html An essential feature I am in need of is setting ...

Convert the existing JavaScript code to TypeScript in order to resolve the implicit error

I'm currently working on my initial React project using Typescript, but I've hit a snag with the code snippet below. An error message is popping up - Parameter 'name' implicitly has an 'any' type.ts(7006) Here is the complet ...

Guide on sending several HTTP requests from a Node.js server with a shared callback function

Is there a way to efficiently make multiple HTTP calls in a Node.js server with a shared callback function? Are there any modules or libraries that can help with this? ...

What could be causing the resolve method to not send any data back to the controller?

While following a tutorial on YouTube, I encountered an issue with incorporating the resolve method getposts into the contactController. Despite my efforts, no value is being returned. I've spent hours searching for answers on Stack Overflow to no av ...

What is the best way to determine if an image already exists in a database where the objects are spread across two distinct SQL tables?

Currently, I am working on a project using classic ASP and SQL. In this project, I have an input box where the image name is entered by the user after clicking the "Update" button. Upon clicking the update button, pre-existing images are displayed in a tab ...

Assistance required in filling out a table solely through JavaScript with input from an HTML form

Hello, I am currently pursuing a second career and have just started learning HTML & JavaScript. For a simple assignment, I need to take user input in the form of numShares and numYears through HTML. My goal is to use JavaScript to populate a 3-column tabl ...

ng-click event not firing after $compile in AngularJS

I'm struggling to get my dynamic HTML elements generated from an AngularJS controller to trigger a function using ng-click. Even after using $compile, the function is not being called. Check out my JS code: var accountApp = angular.module('acco ...

Organize text documents for website display

Is there a way to code a website that will showcase the 20 most recent text files from a directory, in descending order of newest to oldest, and provide links for viewers to access them on the web? ...

Confirm that a certain input is correct using jQuery validation

Is there a way to use jQuery validation to check if a user inputs a value greater than or equal to 5 in a form field? If the value is indeed greater than or equal to 5, an error message should be displayed. How can this be implemented? <input type=&apo ...

"How to ensure a background image fits perfectly on the screen in IE10

I am facing a problem while trying to set the background image in CSS to fit the screen. It works fine with the latest version of Chrome, but there is an issue with IE 10. html { border-top: 10px solid #8A85A5; background: url("http://www.lifeintempe.com/ ...

What is causing setTimeout to not function as intended?

I'm having some trouble moving a <div id="box"> whenever my mouse hovers over it. Currently, the element only moves when I trigger the mouseover event on the div itself instead of when my mouse is actually hovering over it. document.getElements ...

In what ways can I incorporate Django template tags into my JavaScript code?

I've encountered an issue with implementing my model data into a FullCalendar library template in JavaScript. Despite seeing others do the same successfully, I keep getting errors as the template tags fail to register properly. <script> documen ...

Scrolling through menus horizontally

I am faced with a challenge where I have Menu items from Menu1 to Menu10, but the limited space on the web page prevents me from displaying all the menu items at once. Currently, I can only show 4 menu items - Menu4 to Menu7. To access the remaining menu i ...

Try making a series of interconnected fetch requests in Redux Toolkit that rely on the completion of the previous fetch

I am still learning the ropes of Redux and I'm feeling a bit lost. My goal is to make two API calls - one to retrieve an account Id and a category Id, and another to get a list of transactions based on those IDs. The createApi function in my code lo ...