Out of the blue div, could you lend your assistance?

I have a code that displays 5 random images with corresponding text. My challenge is that I want to separate the text into another div so that I can add another function to it, while still keeping the images random with their corresponding text.

<script type="text/javascript">
$(document).ready(function() {
    $(".Image").hide();

    var elements = $(".Image");
    var elementCount = elements.size();
    var elementsToShow = 5;
    var alreadyChoosen = ",";
    var i = 0;
    while (i < elementsToShow) {
        var rand = Math.floor(Math.random() * elementCount);
        if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
            alreadyChoosen += rand + ",";
            elements.eq(rand).show();
            ++i;
        }
    }
});
</script>

<div class="Image"><img   src="image1"/><text id="id1">1</text></div>
<div class="Image"><img   src="image2"/><text id="id2">2</text></div>
<div class="Image"><img   src="image3"/><text id="id3">3</text></div>
<div class="Image"><img   src="image4"/><text id="id4">4</text></div>
<div class="Image"><img   src="image5"/><text id="id5">5</text></div>
<div class="Image"><img   src="image6"/><text id="id6">6</text></div>
<div class="Image"><img   src="image7"/><text id="id7">7</text></div>
<div class="Image"><img   src="image8"/><text id="id8">8</text></div>

Answer №1

It seems like there are some best practices that you may be violating here. Using text as a tag is not valid and it's worth considering if separating the text into another div is necessary. Also, displaying all elements, hiding them, and then showing only 5 randomly selected ones could be simplified by just directly displaying the random 5.

A better approach could be:

<div class="image image1"><img src="image1"/></div>
<div class="text text1"><text id="id1">1</text></div>

<div class="image image2"><img src="image2"/></div>
<div class="text text2"><text id="id2">2</text></div>

Then, in JavaScript, hide both images and texts:

$(".image").hide();
$(".text").hide();

Instead of using elements.eq(rand).show();, you can select based on the id:

$(".image"+(rand+1)).show(); // Adding 1 to rand because it ranges from 0 to 8
$(".text"+(rand+1)).show();

Alternatively, consider grouping elements that will always be displayed together within one div wrapper for easier management.

Answer №2

Here is a collection of images with corresponding IDs:

<div class="Image"><img width="200" height="200"  src="1.jpg"/><div id="id1">1</text></div>
<div class="Image"><img width="200" height="200"    src="2.jpg"/><div id="id2">2</text></div>
<div class="Image"><img width="200" height="200"    src="3.jpg"/><div id="id3">3</text></div>
<div class="Image"><img width="200" height="200"    src="4.jpg"/><div id="id4">4</text></div>
<div class="Image"><img width="200" height="200"    src="5.jpg"/><div id="id5">5</text></div>
<div class="Image"><img width="200" height="200"    src="6.jpg"/><div id="id6">6</text></div>
<div class="Image"><img width="200" height="200"    src="7.jpg"/><div id="id7">7</text></div>
<div class="Image"><img width="200" height="200"    src="8.jpg"/><div id="id8">8</text></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

Height and Width Dilemma in Visuals

Can you help with changing image resolution using jQuery? I have a background image applied to the body using CSS/PHP. My goal is to make the image fill the entire window by applying the screen height and width, without using repeat style. The code I am c ...

Automatic Refresh and Search Functionality on PHP Page

Can anyone help with a problem I'm having trying to implement auto-reload on a page with a table in the form of rows that contain usernames? I am currently using the jQuery searchable plugin from here to search for usernames within the div. The websi ...

Validating the body in Node.js for POST and PUT requests

When working in a production setting, what is considered the standard for POST / PUT body validation? I typically approach it like this: const isValid = (req.body.foo && /[a-z0-9]*/i.test(req.body.foo)) This method involves checking that the var ...

Changing the map behavior when it is moved in Leaflet

I am currently using Leaflet to design a map that includes a personalized sound layer. Each tile on the map features an <audio> element, and I am exploring methods to adjust the audio playback as the user navigates around the map (specifically by mod ...

Is it impossible to access the length property of an undefined variable?

After developing a function that calculates the length of a string entered into an HTML textbox, I encountered an error when trying to display the result in another textbox. The function is designed to get the value from the 5th textbox on my HTML page and ...

Adjusting the content of a span causes the parent element to shift to the left

I'm having trouble finding a solution to a specific issue that seems to be only affecting Chrome. Whenever I try to replace the text in a span element, it causes the parent anchor to shift left. You can see a demonstration of this problem here: http:/ ...

Eliminate the navigation bar option from a website template

Is there a way to permanently eliminate the menu button in this theme? Any guidance would be appreciated. Here's the link to the theme: https://github.com/vvalchev/creative-theme-jekyll-new ...

Tips for creating an editable div that can also incorporate a textarea and the option to upload or delete photos

On my website, users can upload images, names, and descriptions which are saved in a MySQL database. The information is then fetched to display on the website. The code below allows users to enter this information and see it displayed when they click the s ...

The URL may change, but the component remains constant when navigating back

My application consists of two primary components: the Project component and MainContainer. The MainContainer component regularly fetches data using a fetchData method. When moving forward, both the URL and component can change dynamically. However, when m ...

AngularJS: Utilizing ellipsis for text overflow and optimization

As a beginner in angularJS, I might have made some mistakes... Can anyone guide me on how to properly implement this plugin: https://github.com/BeSite/jQuery.dotdotdot on my table? Currently, the performance of my edit form and table is very slow. What c ...

Learn how to configure an Angular2 Template Driven form element by implementing two-way binding and integrating template driven form validation techniques

Can anyone help me figure out the correct way to set up an Angular template driven form element for both validation and two-way binding? I've tried using ngModel in different ways, but cannot seem to achieve two-way binding without encountering issues ...

Managing the display of numerous ngFor components

If you're interested in learning more about the features I will include, here's a brief overview. I plan to have a project section with cards displayed for each project, all populated from a JSON file. When users click on a card on the website, a ...

Is there a simple method to submit to a URL without relying on ajax?

When it comes to using jQuery, the $.ajax() function is typically used for POST requests to a URL. However, in my particular situation, I am unable to use this function. I need the client to send a POST request to a URL and have the server redirect the use ...

Utilizing a for loop to iterate through an array based on its length

Just delving into the world of JavaScript and recently grasped the concept of For loops. I have a variable that holds an array with a list of first names, and my goal is to add last names to each of them. Here's the code snippet I came up with: l ...

Having trouble getting the CSS Hover state to function properly?

I am currently working with a code snippet that looks like this: <div style="position: absolute; margin-left: -22px; margin-top: -22px; left: 502px; top: 379px; z-index: 380; display: block;" class="maptimize_marker_0 f st">1<span class="pinlabel ...

Adjustable height for the absolute element

Having a bit of an issue with the height of the absolute div. About: .wrapper - I want the wrapper to automatically adjust its height but be limited by a max-height. (No scrolling for the wrapper) .title - Just a title .content - The problem aris ...

Exploring a collection of objects using a filter and specific keyword

I am looking to implement a search functionality in JavaScript using an array, filter, and keyword. The goal is to search through the array based on the filter and keyword provided, and return a new array of objects similar to the original one. var data ...

What is the best way to save a JSON stream to a file in Node.js?

I am facing an issue with writing a complete JSON object to a file as it is received. Currently, I am using const file = fs.createWriteStream('./example.file'); var inputStream = JSON.parse(generatedData); fs.write(inputStream+"\n"); The d ...

What is the best way to adjust the priority of elements using JavaScript in an ASP.NET MVC application?

As part of my application, I need to create a function that allows for the changing of deputy priorities for each consultant. Here is what I have implemented so far: View: @model ML.Domain.DAL.DB_CONSULTANTS .... <table> <tr> < ...

The function fs.createReadStream does not exist

Snippet to Submit Career Form: import axios from 'axios'; import FormData from 'form-data'; var fs = require('fs'); submitCareerForm(e){ e.preventDefault(); let formData = new FormData(); //formdata obje ...