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

Interested in compressing CSS and JavaScript using PHP, but uncertain about the impact on performance and the best methods to implement it?

My current approach involves using PHP to combine multiple css (or js) files into a single file, while also compressing the content using GZIP. For example, the HTML page makes calls to resources like this... <link rel="stylesheet" href="Concat.php?fi ...

Trouble parsing JSON in Classic ASP

After receiving a JSON Response from a remote server, everything looks good. I discovered an helpful script for parsing the JSON data and extracting the necessary values. When attempting to pass the variable into JSON.parse(), I encountered an error which ...

Passing Props from _app.js to Page in ReactJS and NextJS

I recently made the switch from ReactJS to NextJS and am encountering some difficulties in passing props from _app.js to a page. My issue lies in trying to invoke a function in _app.js from another page. In ReactJS, this process was simple as you could cr ...

javascript issue with setting the id attribute on a select option

I can't seem to set the id attribute in my select element using JavaScript. When I inspect it, the id attribute isn't showing up... Here's the first method using JS: var selectorElem = document.getElementById('selector') var ...

What is the best way to implement an anchor link in my JavaScript code?

I'm struggling to wrap my head around this, as my thoughts seem to have vanished. On my webpage, there's a button element with an id: for example <button id="someId"></button> Within the document.ready function, I've set up an ...

A guide to retrieving JSON data with Javascript

I'm in the process of building a small website for weather forecasting. However, I've encountered an issue when trying to retrieve JSON data from accuWeather - I'm not getting any response. I've double-checked my request and it seems to ...

What steps should I take to fix the error message "Uncaught TypeError: Class constructor m must be called with 'new'" that occurs while attempting to access a polymer v2.0 application?

Is there a way to resolve this error that occurs when attempting to open a Polymer v2.0 app on Safari in iOS? Uncaught TypeError: Class constructor m cannot be invoked without 'new' from custom-elements-es5-adaptor. The Polymer v2.0 starter k ...

Exploring the capabilities of incorporating multiple nested if-else statements in an AJAX/JavaScript function

Can anyone help me with this code issue? I am trying to run a function with data received from a CI controller to ajax, but having trouble with multiple if else statements. The code works fine with one if else statement, but not with nested or multiple one ...

Is the Date Epoch a reliable form of unique identification?

Currently, I'm developing a Node API and encountered a situation where I need to create a unique 15-digit random number for a model without using autoincrement. The challenge is to ensure that the generated number is not trivial. I am hesitant about ...

Warning: multiple selections have been made on the checkboxes

Currently, I am using FormData to submit data and trying to alert the values of checked checkboxes in my form. At the moment, I can only make it work for one checkbox. How can I alert the values of all checked checkboxes? var formData = new FormData(docu ...

What is the best way to update the content of a div on an HTML page by incorporating the content of a div from a different page using JavaScript?

I have a requirement where I need to implement a link in a Table of Contents that, upon clicking, should replace the existing content of one div on a page with the content of another div on a different page. My goal is to accomplish this using only JavaScr ...

What is the solution for getting `overflow-x` to function in place of `overflow-y`?

I have a main container with several sub-containers inside. When the main container's width exceeds its limit, I want to display a horizontal scroll bar. Instead of using the 'display: inline-block' property because it creates unwanted whit ...

Tips for presenting hierarchical information from my database in ejs

I'm currently working on a genealogy application using node js express and ejs but I'm facing an issue with displaying the database in order (starting from parent). This is the code snippet for retrieving my data and what I see when I log the ou ...

Designing a unique customized top navigation bar in Magento 1.9.2

I recently attempted to create a unique top menu in magento 1.9.2 by modifying the Navigation.php file located at app/code/core/Mage/catalog/Block/. I added some custom classes in an effort to customize the menu. In order to achieve this customization, I ...

Issue with CSS files in Jest"errors"

I'm currently facing an issue while trying to pass my initial Jest Test in React with Typescript. The error message I am encountering is as follows: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.App ...

What methods can be used to modify the appearance of the cursor depending on its position?

Is there a way to change the cursor to a left arrow when on the left half of the screen and switch it to a right arrow when on the right half, using JavaScript? I am trying to achieve something similar to what is shown on this website. I attempted to acco ...

Personalizing the fileTemplate selection in FineUploader

My English is not the best, so apologies in advance. I'm struggling to customize the FineUploader FileTemplate option. I don't want to use fineUploaderBasic; I want total customization. Initially, I managed to hide the file name and size after a ...

When the component is initialized, the computed property is not being evaluated

My maps component initializes a Google map, adds markers based on props passed from the parent, and sets the correct bounds of the map. However, the markers are added through a computed property to make it reactive. Everything seems to be working fine, exc ...

Using JQuery for sliding left without having to use inline CSS

I am dealing with a situation on my website where I need to hide a sidebar when clicked. $('#sidebar').toggle('slide', 'left', 300) In addition, I have implemented a CSS style to hide the sidebar on mobile devices. #sidebar ...

Guidance on implementing a source map in a Node.js VM

Currently, I am analyzing JavaScript bundled source code in Node.js using the following snippet of code: const javascriptCode = "..." const javascriptSourceMap = "..." const wrapper = NativeModule.wrap(javascriptCode); const script = ne ...