My code is designed to operate exclusively on the initial element containing an ID

Check out this screenshot to see what I'm aiming for.

I discovered a solution online that might help me achieve my goal.

To test the solution, I set up a simple HTML structure like this:

<div id="block">
    <img
    id="img" class="cimg" src=
    "http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>

<div id="block">
    <img
    id="img" class="cimg" src=
    "http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>

<div id="block">
    <img
    id="img" class="cimg" src=
    "http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>

Here's the Javascript code I used:

function averageColor(imageElement) {

        // Create canvas element
        var canvas
            = document.createElement('canvas'),

            // Get 2D canvas context
            context
                = canvas.getContext &&
                canvas.getContext('2d'),
            imgData, width, height,
            length,

            // Store individual color values
            rgb = { r: 0, g: 0, b: 0 },

            // Total number of colors
            count = 0;

        // Set canvas height and width
        height = canvas.height =
            imageElement.naturalHeight ||
            imageElement.offsetHeight ||
            imageElement.height;
        width = canvas.width =
            imageElement.naturalWidth ||
            imageElement.offsetWidth ||
            imageElement.width;

        // Draw image on canvas
        context.drawImage(imageElement, 0, 0);

        // Get image data
        imgData = context.getImageData(
                    0, 0, width, height);

        // Get image data length
        length = imgData.data.length;

        for (var i = 0; i < length; i += 4) {

            // Sum red color values
            rgb.r += imgData.data[i];

            // Sum green color values
            rgb.g += imgData.data[i + 1];

            // Sum blue color values
            rgb.b += imgData.data[i + 2];

            // Increment total color values count
            count++;
        }

        // Calculate average color values
        rgb.r
            = Math.floor(rgb.r / count);
        rgb.g
            = Math.floor(rgb.g / count);
        rgb.b
            = Math.floor(rgb.b / count);

        return rgb;
    }

    // Function to set background color of div
    var rgb;

    setTimeout(() => {
        rgb = averageColor(
            document.getElementById('img'));

        // Select element and set background color
        document
            .getElementById("block")
            .style.backgroundColor =
            'rgb(' + rgb.r + ','
            + rgb.g + ','
            + rgb.b + ')';
    }, 500)

Essentially, I created divs containing images and used Javascript to apply backgrounds. However, this method only worked on the first div and not the others. I tried using a loop without success:

    var rgb;
    var imgg = document.getElementsByClassName("card1");
    var i;
    for (i = 0; i < imgg.length; i++) {
        rgb = averageColor(document.getElementById('img'));
  
        // Select element and set its background color
        document
            .getElementById("block")
            .style.backgroundColor =
            'rgb(' + rgb.r + ','
            + rgb.g + ','
            + rgb.b + ')';
    }

If anyone has any ideas or solutions, please let me know!

Answer №1

It's important to make sure each HTML element has a unique ID. Instead of repeating IDs, consider using classes.

<div class="block">
<img class="cimg" src="http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>

<div class="block">
    <img class="cimg" src="http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>

<div class="block">
    <img class="cimg" src="http://localhost:90/Get%20average%20color%20of%20image%20via%20Javascript/Archive.jpg">
</div>

Additionally,

var rgb;
var imgg = document.getElementsByClassName("cimg");
var blocks = document.getElementsByClassName("block");
var i;
for (i = 0; i < imgg.length; i++) {
    rgb = averageColor(imgg[i]);

    blocks[i].style.backgroundColor =
        'rgb(' + rgb.r + ','
        + rgb.g + ','
        + rgb.b + ')';
}

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

Obtain a masterpiece by creating a canvas in React

Greetings! I have developed a drawing app using react and I am looking for a way to capture what the user has drawn on the canvas when they release the mouse button. This process should repeat continuously until the user stops drawing. Can anyone suggest h ...

Looking for assistance in extracting text within a span element in a Python project using XPATH and PhantomJS. Any takers?

Seeking Assistance! I am attempting to extract "RC0402JR-070RL" from the HTML provided below. Here is the HTML code snippet: <td class="tr-mfgPartNumber"> <a itemprop="url" href="/product-detai ...

Transmit an array of JavaScript objects using Email

Within the code layout provided with this post, I have executed various operations in JavaScript which resulted in an array of objects named MyObjects. Each object within MyObjects contains properties for Name and Phone, structured as follows: MyObject ...

What is the best method for utilizing the CSS :target selector in order to generate a versatile modal box?

I am looking for a way to display my vast collection of proverbs from an endangered language without overcrowding the page. I have implemented a modal box solution using CSS :target selector, which expands a hidden div element when clicked on. However, I n ...

Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing? Below is the code snippet: HTML <div *ngIf="tempThermometer | async as temp; else loading"> <ng-container *ngIf="temp.length !== 0; else noItems"> &l ...

Generating dynamic forms using JSON Schema in Angular 8 can greatly streamline the form creation process

Struggling with generating dynamic forms from JSON Schema in Angular 8, I stumbled upon a couple of libraries. One seemed outdated with its last commit around 2 years ago, while the other appeared to be a more recent fork of it for Angular 8. The first li ...

jQuery classes fail to display effects when added

My HTML code is shown below: <div class="container"> <!-- Example row of columns --> <div class="row"> <div class="span7"> <div class="home-image left-image"> <img class="photograp ...

Somehow, my array only manages to traverse exactly half of its elements

Something odd is happening with my input tag in the HTML file where only half of my array elements are being processed. The input collects numbers/letters and assigns a line of code, like this: let result = Object.fromEntries( Object.entries(answers2).m ...

Creating a grid layout that activates an image when clicked using JavaScript

I've successfully implemented a gridview with an image column, but I'm looking to enhance the functionality. Specifically, I want to enlarge the clicked image and bring it into focus on the screen. I've managed to achieve this when the image ...

How to troubleshoot missing API data in a Bootstrap 5 modal

I am currently working on a project involving a Pokemon API where I have successfully built the front end using .fetch(). My goal is to create an additional modal that displays some stats. However, I am struggling to get the data from the API to show up in ...

Customizing the color of cells in an HTML table within a JSON based on their status

Would you like to learn how to customize the color of cells in an HTML table based on the status of a college semester's course map? The table represents all the necessary courses for your major, with green indicating completed courses, yellow for cou ...

Unable to perform queries from a separate file as connection.query function is not recognized

Currently diving into node.js and databases. Attempting a mysql query, but encountering the error TypeError: connection.query is not a function. Utilizing Node MySQL 2 (https://www.npmjs.com/package/mysql2) package; The connection and queries in app.js f ...

Encountering a RangeError in FusionCharts with VueJS, I faced the issue of exceeding the maximum call stack size while trying to

After inserting a clip array into xAxis, I encountered a RangeError. Has anyone else experienced this issue? I have set up a repository to demonstrate the bug: https://github.com/Ic3m4n34/fusioncharts-bug (App.vue) Does anyone have suggestions on how to ...

Retrieve the updated file name from the mini file upload form

I have implemented the Mini AJAX Upload Form from this tutorial to upload files to a server. I made modifications to add a timestamp at the end of the file name. How can I return the updated file name (with the timestamp) back to the client for future refe ...

What is the best way to send an observable with parameters through @Input?

The objective is to transfer an http request from Component 1 to Component 2 and initialize its parameters on Component 2. Here is a pseudo code representation of my approach: Component 1 HTML <app-component-2 [obs]="obs"></app-component-1> ...

The markers from KML exported from My Maps are not showing up on the Google Maps JavaScript API

I have a map on Google My Maps that I want to showcase through the Google Maps JavaScript API. This way, I can easily merge multiple maps into one and add paths/markers without needing to code it all manually. Test out the map I'm using by clicking t ...

What mistakes did I make in my Ajax code?

My aim is to dynamically add items to my listbox when a button is clicked, and then retrieve the value of the added item in the listbox using ajax. Below is the code I have tried: $('#right').click(function () { alert("Start process"); ...

What are some ways to optimize a range slider for touch screen usage?

I'm currently working on a small project and encountering an issue where the animation duration of an element needs to be changed using a range slider. The functionality works fine on desktop screens but doesn't seem to work on mobile devices. ...

Encountering difficulty transforming DataFrame into an HTML table

I am facing difficulties incorporating both the Name and Dataframe variables into my HTML code. Here's the code snippet I have: Name = "Tom" Body = Email_Body_Data_Frame html = """\ <html> <head> </he ...

What is the process for subscribing to setInterval() in an Angular application?

I'm currently working on developing an iOS location tracking application using the Ionic 5 Framework, Angular, and the Cordova Geolocation Plugin. In the past, I was able to track user location changes using the watchPosition() function, which worked ...