Manipulate an image using JavaScript to change its color to white when clicked

I have a collection of images that I want to change to white when clicked, creating a fade effect. Essentially, when the image is clicked, it should transition from its original state to being completely white for a second. Additionally, I need the image to revert back to its original form when something else is clicked by the user.

Can this be achieved using JavaScript? If so, what specific aspects should I focus on (I struggle with graphics)?

I attempted to use opacity to accomplish this, but I do not want the background to show through the image.

Answer №1

Creative Solution Using Pseudo-elements

If you're looking for a unique way to overlay content, consider using a wrapper with a pseudo-element. This approach allows you to add animations that are efficiently controlled by a toggled CSS class, ensuring optimal performance.

Check out this CodePen demonstration for a visual example.

HTML

<div class="whiteclicker">
  <img src="http://lorempixel.com/400/200" alt=""/>
</div>

SCSS

@import "compass/css3/transition";

body { background: gainsboro; text-align: center; }

.whiteclicker {
  display: inline-block;
  position: relative;
  &::after {
    content: "";
    display: block;
    position: absolute;
    top:0; left:0; right:0; bottom:0;
    background: white;
    opacity: 0;
    @include transition(opacity 1s ease);
  }
  &.active::after {
    opacity: 1;
  }
}

JS

$('.whiteclicker').click(function(){
  $(this).toggleClass('active');
});

Answer №2

In an effort to improve upon Spencer Wieczorek's solution (I believe that using two is the best option in my opinion):

Have you considered dynamically creating a white div element (and fading it in and out) instead of including it directly in the HTML code?

Check out the code example.

$("#myImage").click(function(){
    $(this)
    .parent().css({position:'relative'}).end()
    .after($('<div>')
           .hide()
           .css({position:'absolute'
                 , top: $(this).position().top
                 , left: $(this).position().left
                 , width: $(this).width()
                 , height: $(this).height()
                 , background: '#FFF'
                })
           .fadeIn('fast')
           .on({
                click : function(e){
                   $(this).fadeOut('fast', function(){ $(this).remove();});
                }
           })
          );
});

This way, you won't need to make any additions to the HTML code or CSS styles as jQuery handles everything.

@Spencer Wieczorek: I provided my own solution because I disagreed with your approach to designing the CSS style (fixed positioning may not be ideal, especially if the page is scrolled, for instance...). Mine is more independent and adaptable ;)

Answer №3

If you're looking to create a cool effect with images, consider stacking two images on top of each other. Here's a simple way to achieve this:

<script type="text/javascript">
var image1 = '<img class="images" src="Image 1" onClick="switch();" />';
var image2 = '<img class="images" src="Image 2" onClick="switch();" />';
var currentImage = 1;
function switch(){
     if(currentImage==1){
         currentImage++;
         document.getElementById("image").innerHTML = image2;
     }
     if(currentImage==2){
         currentImage--;
         document.getElementById("image").innerHTML = image1;
     }
}
</script>
<style>
     .images{ position:fixed; top: 0; left: 0; }
</style>
<img class="images" src="Black image" />
<div id="image"><img class="images" src="Image 1" onClick="switch();" /></div>

To add a fading effect to your images, here's a snippet that demonstrates how you could achieve it:

<script type="text/javascript">
var fadecount = 100;
function fade() {
    document.getElementById("imageToFade").style.opacity = fadecount;
    fadecount--;
    if(fadecount==0){
        clearTimeout(fade);
    }
}
function start_fade(){
    var fade = setTimeout(fade(), 10);
}
</script>

Answer №4

By utilizing Base 64, you can store the binary version of an image along with an all white picture. When a user clicks on the image, the source is switched to the white base64...

In this scenario, JavaScript dynamically changes the source to the all white version upon clicking, eliminating the need for multiple elements existing on different layers.

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 importing the TokenExpiredError that is thrown by the verify function in jsonwebtoken?

Is there a way to determine if an Error object thrown by the jwt.verify function in the jsonwebtoken library is of type TokenExpiredError using Typescript's instanceof? For example: import jwt from "jsonwebtoken"; function someFunction() { try { ...

Experiencing difficulty in successfully updating a React child component when the prop passed from the parent component is

In the backend implementation, I have successfully set up a socket.io, Node, Express configuration that has been tested to work correctly. It is emitting the right number of broadcasts to the appropriate client using socket.emit("team_set", gameI ...

Align content at the center of header with a colored background

I recently came across a Bootstrap template that features a transparent navbar and a stunning background image. I am utilizing bootstrap-vue, which simplifies the process with elements like <b-container> serving as shortcuts for standard Bootstrap st ...

After using browserify, when attempting to call the function in the browser, an Uncaught ReferenceError occurs

I am currently in the process of creating a compact NPM package. Here is a basic prototype: function bar() { return 'bar'; } module.exports = bar; This package is meant to be compatible with web browsers as well. To achieve this, I have inst ...

Syntax error triggered and caught by ajaxError

I have implemented a client-side ajax error handler using the following code: $(document).ajaxError(processAjaxError); $.getJSON('/data.json'); In the server side, I have defined a function as shown below: def get(self): self.response.he ...

How to place the Google Custom Search box on top of an image in a Wordpress page using HTML code

I'm looking to design a WordPress page where I can input HTML code to achieve the following: 1) Implement a Google custom search box (I will obtain the GCS code from Google) that overlays an image hosted in my site's media library, not positione ...

Using Vue.js to filter a list based on index matches

I need help with synchronizing two lists. The first list is displayed in a carousel format, and the second list contains details corresponding to each card in the carousel. I have successfully implemented logic to track the current index of the displayed c ...

Is it beneficial or detrimental to utilize a HTML Form?

Is it permissible to have 1 text box and 2 Label elements that are associated with that one textbox? Imagine the Textbox as a search field. The two Label elements represent two distinct categories you can conduct searches in. Clicking on Label 1 would foc ...

A guide to effectively utilizing FocusIn and FocusOut for the complete functionality of the PrimeNG tree widget

Issue: I am encountering a problem with my primeng tree component inside a div. The desired behavior is that when I click on a tree node, the focusin event should be triggered only once (subsequent clicks on other nodes shouldn't trigger focusin as it ...

What causes two elements with display: inline-block; position: absolute; to overlap instead of appearing side by side?

It is recommended to use position: relative; in order to achieve inline block behavior for both elements and prevent them from overlapping. This positions the elements inline next to each other as they are recognized as blocks. When using position: absolu ...

Issue with responsive image display on Android device with Chrome browser

Check out my code snippet for a responsive image display: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>xxxxx</title> < ...

Is there a way to prevent links from opening in an iframe and have them open in the main window instead?

Imagine you have an iframe on your webpage: <iframe style="border-radius:15px;" width="190" height="450" frameborder="0" scrolling="no" marginheight="5" marginwidth="10" src="../img/interactive_map/interactive_sverige.htm"> </iframe> ...

Implementing Async Detect Series for Output Retrieval in Node.js

I'm looking to implement a process where I can return output based on asynchronous calls while iterating through an array. The goal is to stop the iteration once a desired response is obtained from a Third Party Server and return that response. To ac ...

Tips for modifying the size of your input

I'm currently utilizing components from and I'm looking to modify the length of the input box to match the black box seen here: https://i.sstatic.net/RWYTU.png In the image, you can observe that the input box should be equal in length to the b ...

Every time I hover, my jQuery code keeps repeating the hover effect

I am currently facing an issue that has me stumped on finding a solution. The problem arises when I hover over the .div multiple times, the animation just doesn't stop and keeps running continuously. What I aim for is to have the .hidden element fad ...

Is it possible to execute an Ajax Request using JQuery?

I've been attempting to update the content within a <div> using a JQuery Ajax Call, but unfortunately I'm encountering some difficulties. Whenever I click on the onclick <a> element, nothing seems to happen. Below is the code that I a ...

Enable or disable multiple input options based on dropdown selection changes

I am currently working on a feature where multiple text boxes need to be enabled or disabled based on the selection made in a dropdown box. What I want to achieve is that regardless of which option is selected in the dropdown, all fields should be enable ...

What is the best way to remove the help button on the WordPress dashboard?

Being a beginner in Wordpress, I am trying to figure out how to hide the help button on the top right of the dashboard in the admin backend without resorting to plugins or code removal. My plan is to simply add display:none to a CSS file, but I am having ...

What steps should I take to resolve my header issues post upgrading to Bootstrap 4?

After updating my Bootstrap files, I noticed that my Navbar is broken. I have been diligently checking and revising my code to align with the documentation on their official website, but I just can't seem to pinpoint what's missing. Initially, I ...

Initiate the typeahead drop down menu by pressing the downward key and then navigate through the options within the drop down

Utilizing the bootstrap typeahead feature within my angular project has been a game-changer. I needed a way to activate the typeahead drop down by pressing the down key when no text had been entered yet. By following guidance from this resource, I was able ...