Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change an image with onclick()

I want to change an image to some other image when i click on the object. the code is stacked in the following order:

<li><img><some text></img></li>
<li><img><some text></img></li>
<li><img><some text></img></li>
<li><img><some text></img></li>
<li><img><some text></img></li>

What I wish to do is, when I click on the <li> i want to change the image to a coloured version of the image, i.e. some other image. Now, I know I can use JQuery/JS to accomplish it. But I don't want a huge amount of JS code to accomplish something so simple.

Can it be done using something simpler? Like pseudo selectors? .active class?

I cannot seem to think of it.

like image 571
amit Avatar asked Jul 20 '11 16:07

amit


3 Answers

To change image onclik with javascript you need to have image with id:

<p>
    <img alt="" src="http://www.userinterfaceicons.com/80x80/minimize.png" 
        style="height: 85px; width: 198px" id="imgClickAndChange" onclick="changeImage()"/>
</p>

Then you could call the javascript function when the image is clicked:

function changeImage() {
    if (document.getElementById("imgClickAndChange").src == "http://www.userinterfaceicons.com/80x80/minimize.png"){
        document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/maximize.png";
    } else {
        document.getElementById("imgClickAndChange").src = "http://www.userinterfaceicons.com/80x80/minimize.png";
    }
}

This code will set the image to maximize.png if the current img.src is set to minimize.png and vice versa. For more details visit: Change image onclick with javascript link

like image 175
Markweb Avatar answered Nov 09 '22 07:11

Markweb


Or maybe and that is prob it

<img src="path" onclick="this.src='path'">
like image 24
anymousse Avatar answered Nov 09 '22 08:11

anymousse


How about this? It doesn't require so much coding.

$(".plus").click(function(){
 $(this).toggleClass("minus")  ; 
})
.plus{
    background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_blue.png");
    width:130px;
    height:130px;
    background-repeat:no-repeat;
}

.plus.minus{
    background-image: url("https://cdn0.iconfinder.com/data/icons/ie_Bright/128/plus_add_minus.png");
    width:130px;
    height:130px;
    background-repeat:no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#"><div class="plus">CHANGE</div></a>
like image 10
Bel Avatar answered Nov 09 '22 06:11

Bel