456543646346
456543646346

Reputation: 993

change image border color onclick

I have a page where the users needs to pick a color for a tshirt.

When the user selects a color, I want the image's border color to change to green.

And if the user click a different color, it needs to put back the default border color and change the border color of the new image that was clicked.

Any idea how I could do that ?

Upvotes: 0

Views: 18621

Answers (2)

Yogendra Singh
Yogendra Singh

Reputation: 34387

Say your image is displayed using img tag as below:

  <img name="img01" id="img01" src="image.gif" border="2" bordercolor="#000000">

implement onClick fnction fnChangeBorder as below

   function fnChangeBorder(){
      document.getElementById("img01").style.borderColor="#00FF00";
   }

or

   function fnChangeBorder(){
      var imgElement = document.getElementById("img01");
      imgElement.setAttribute("style:borderColor", "#00FF00");
   }

or you can define a style class and do like:

   function fnChangeBorder(){
      document.getElementById("img01").style.className="greenClass";
   }

EDIT:

For multiple images, with indexed id, we can pass the index in the onclick function as:

  <img name="img1" id="img1" src="image.gif" border="2" bordercolor="#000000"
        onclick="javascript:fnChangeBorder(1);">

  <img name="img2" id="img2" src="image.gif" border="2" bordercolor="#000000"
        onclick="javascript:fnChangeBorder(2);">

And update fnChangeBorder as:

   function fnChangeBorder(index){
      document.getElementById("img"+index).style.className="greenClass";
   }

For multiple images, with non-indexed id, we can pass the id in the onclick function as:

  <img name="imgabc" id="imgabc" src="image.gif" border="2" bordercolor="#000000"
        onclick="javascript:fnChangeBorder('imgabc`);">

  <img name="imgxyz" id="imgxyz" src="image.gif" border="2" bordercolor="#000000"
        onclick="javascript:fnChangeBorder('imgxyz');">

And update fnChangeBorder as:

   function fnChangeBorder(imageId){
      document.getElementById(imageId).style.className="greenClass";
   }

Upvotes: 3

Exception
Exception

Reputation: 8389

Create one class with your styles. For example

.selected{
   border : 1px solid green;
}

Then apply the className on click of the item. Avoid using setAttribute to set Class name of a item. It is having some issues. Then onclick of the image remove the selected class name on all items and then apply class name selected to the target image.

Upvotes: 1

Related Questions