Why are the random colors blending into the image?

After watching a tutorial on the YouTube channel Online Tutorials titled "Change Image Color Vanilla JavaScript," I am confused as to why some random colors from the click event are overlapping the image instead of just changing the color of the cat's eye. Is there a solution to this issue? Perhaps I need to use a different image that is more suitable for this specific functionality. Additionally, I find some parts of the code, especially the one I left a comment on, quite challenging to comprehend. Any assistance in understanding these aspects would be greatly appreciated. Thank you.

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Change image color"</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>

    <img src="images/cat-2143332_1920.jpg" alt="">

    <div id="bg"></div>

    <script type="text/javascript">
        const bg = document.getElementById('bg');
        function randomColor() {
            return Math.floor(Math.random() * 255);
        }
        // I don't understand how this section works??
        bg.addEventListener('click', () => {
            bg.style.backgroundColor = 'rgba(' + randomColor() + ',' + randomColor() + ',' + randomColor() + ')';
        });
    </script>
</body>

</html>

CSS

*{
    margin: 0;
    padding: 0;
}
body{
    overflow: hidden;
}
img{
    display: block;
    width: 100%;
}
#bg{
    position: absolute;
    top: 0;
    width: 100%;
    height: 100vh;
    mix-blend-mode: hue;
}

https://i.stack.imgur.com/Wm3G9.jpg

Answer №1

The background changes behind the image due to a unique blend mode called hue. For more information on CSS blend modes, you can visit this link. Feel free to experiment with different blend modes to achieve various effects.

The confusing line in your code simply generates a random color using RGBA notation. The values for Red, Green, and Blue range from 0 to 255. You can try running the provided code snippet in the developer console multiple times to see how it generates random colors.

function randomColor() {
            return Math.floor(Math.random() * 255);
        }
console.log('rgba(' + randomColor() + ',' + randomColor() + ',' + randomColor() + ',1.0)');

Regarding the strange bug you mentioned, have you checked if it still exists in the code found at this link? I included a user-select:none property in the CSS to address any potential issues.

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

What is the process for producing multiple objects in JSON format and then accessing them from within <g:javascript> in Grails?

My goal is to add two select boxes within the results div using Ajax. I have a function named ajaxFun that retrieves values for the select boxes. However, I am struggling with rendering multiple objects as JSON and then retrieving them in my JavaScript fun ...

I am experiencing issues with my Vue.js application when trying to send an HTTP POST request

I am encountering an issue in my Vuejs application while trying to send an HTTP POST request to my server. The error message that keeps popping up in the console is: TypeError: _api__WEBPACK_IMPORTED_MODULE_0__.default.post is not a function at Object ...

Tips for preserving @typedef during the TypeScript to JavaScript transpilation process

I have a block of TypeScript code as shown below: /** * @typedef Foo * @type {Object} * @property {string} id */ type Foo = { id: string } /** * bar * @returns {Foo} */ function bar(): Foo { const foo:Foo = {id: 'foo'} return f ...

What is the best way to combine two arrays of objects in AngularJS?

How can I merge the existing object array with another one in AngularJS to implement the "load more" feature? Specifically, I want to add the AJAX response to the existing data each time. Currently, I have a variable called $scope.actions that holds the ...

Having trouble with installing Recharts through npm

When I try to install recharts using npm, I encounter the following error message in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! ...

What steps should I take to fix my responsive media query?

I am currently working on fixing some responsive issues on my WordPress website. Previously, in mobile view, it looked like this: https://i.stack.imgur.com/vpvHy.jpg After adding the following code to the CSS of my child theme: @media only screen a ...

The SetInterval function will continue to run within a web component even after the corresponding element has been removed from the

I am currently engaged in developing a straightforward application that coordinates multiple web components. Among these components, there is one that contains a setInterval function. Interestingly, the function continues to run even after the component it ...

The active class consistently adds new menu options without removing the previous ones

I am facing an issue with my menu where the active class does not get added to the new menu item when clicked, despite being removed from the previous item. Below is the code snippet: <div class="row text-center" id="side-menu"> <nav> ...

How can the .pre() middleware function in Mongoose be utilized?

I'm curious about the use cases for mongoose .pre('validate') and .pre('save'). I understand their functionality, but I'm struggling to think of specific scenarios where I would need to utilize them. Can't all necessary a ...

Split an array of simple data types in JavaScript into separate sections

Is there a way to divide an unordered array of primitive types into specific segments like this: var array = [102,103,104,201,203,204,303,301,302,405,406,408,101]; => newArray = [[101,102,103,104],[201,203,204],[303,301,302],[405,406,408]] The divisio ...

Issue encountered while attempting to log out a user using Keycloak in a React JS application

I'm currently working on implementing authentication for a React JS app using Keycloak. To manage the global states, specifically keycloackValue and authenticated in KeycloackContext, I have opted to use React Context. Specific Cases: Upon initial r ...

What are the steps for retrieving data on the server side by utilizing a token stored in localStorage?

Currently, I am diving into the official documentation for Next.js and utilizing the App router. On the data fetching patterns page, it explicitly states: Whenever possible, we recommend fetching data on the server To adhere to this recommendation, I cr ...

I am in search of a method to rephrase the content while minimizing redundancy

I am looking to improve the code for handling two different conditions in the UI. Can someone suggest a better way to rewrite it? <i *ngIf="measures.length > 0"> <ul *ngFor="let m of measures"> <io-data-selection-row [text] ...

Setting a const value (true or false) based on the size of the window - a step-by-step guide

While studying, I encountered a challenge: In the code below, I need to dynamically set useState(false) based on the screen size. If the screen is larger than 947px, for instance, it should automatically be changed to true. The issue arises because sett ...

Steps for creating a horizontal card design

Looking to achieve a card style similar to this: http://prntscr.com/p6svjf How can I create this design to ensure it remains responsive? <div class="recent-work"> <img src="work/mercedes.png"> <h3>Modern website concept</h3&g ...

Dealing with Class and Instance Problems in Mocha / Sinon Unit Testing for JavaScript

Currently, I am working on unit testing an express middleware that relies on custom classes I have developed. Middleware.js const MyClass = require('../../lib/MyClass'); const myClassInstance = new MyClass(); function someMiddleware(req, ...

Using Javascript to transmit audio via a microphone

I am currently trying to use Selenium to simulate a user on a website that features audio chat. My goal is to emulate the user speaking through the microphone. While I have come across several resources discussing how to listen to the microphone in JavaSc ...

Checking the response from an AJAX call with an if/else statement

Is there a way to create a counter for unread messages using PHP and jQuery? Below is the PHP code in BubbleStat.php: $totalMsg = $mysql->totalRows("SELECT msg_id from messages WHERE msg_opened = 0 AND msg_receiver = '".$_SESSION["ActiveUserSessio ...

Hide elements in hidden divs until the page is fully loaded to reduce initial page

www.prismasites.com I am creating a unique world map by using SVG DIVs shaped like Continents. Upon clicking on a continent on the world map, it conceals the world map DIV and displays the respective continent DIV with SVG. I have successfully achieved ...

What could be the reason behind the for loop not incrementing and the splice not being modified in my code?

Encountered a seemingly simple problem while coding, but the expected returns started deviating as I progressed. Your assistance would be greatly appreciated. If you do provide help, please elaborate on your approach and where I hit a roadblock. The Chal ...