How to change image when clicking? [duplicate]


I have a course work and I had the following idea:

There are several images that will represent the chairs of a cinema (all are the same images, the same are in my HTML file), and I want to make the effect of when the user clicks on one of them it changes color symbolizing that he chose that chair.

I want the "onClick" to be used so that it calls another image when clicking on the images that are appearing for the user or it will call the same image only of different color.

I want it to be by this method but I do not know if it's possible, if not, show me the best way to do it.

My HTML file


    <img src="imagens/cadeiraAzul.png" id="cadeira1" onclick="">


My JS file

function cor(){

As a beginner in this area you will probably have tools unknown to me so if you can explain what each one does, I'll be even more grateful.

I also need if the user clicks again it changes to the image that was initially, in case it is chosen by mistake.

asked by anonymous 19.01.2017 / 20:02

2 answers


You can leave each style in different classes, and then change the class as per the click, using the property className of the javascript.

In this example, I left it as a toggle, because the user can select and de-select the chair:

function marcar(e) {
  // verifica se a classe azul (estilo css que conter a imagem azul) esta no elemento
  if (e.className == "azul") {
    e.className = "vermelho";
  } else {
    e.className = "azul";
.azul::after {
  content: url("");
.vermelho::after {
  content: url("");
  <img class="azul" id="cadeira1" onclick="marcar(this)">
  <img class="azul" id="cadeira2" onclick="marcar(this)">
  <img class="azul" id="cadeira3" onclick="marcar(this)">

The onclick action will go to function the scope of the element that was clicked. To leave the code cleaner, instead of leaving the images in the source (src), I left in specific classes, which I called "blue" and "red". When we click on the image, we check if the element in question ( e , passed by parameter) has the class blue ( e.className == 'azul' ) - if yes, it substitutes for class .vermelha , which contains the red image.

19.01.2017 / 20:11

If you want to learn more about the Jquery framework. Here's the implementation running of your question in the fiddle .


    <img alt="" src=""style="height: 85px; width: 198px" id="imgBandeira"  />



    if($(this).attr("src") == "") 

19.01.2017 / 20:21