Home  >  Q&A  >  body text

Change image via onclick() function

<p>I want to change one image to another when clicking on the object. Codes are stacked in the following order: </p> <pre class="brush:php;toolbar:false;"><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></pre> <p>What I want is that when I click <code><li></code>, the image changes to a color version of the image, which is another image. Now, I know I can do it using JQuery/JS. But I don't want to add a lot of JS code to achieve such a simple function. </p> <p>Is there an easier way to do this? Methods like the pseudo-selector<code>.active</code> class? </p> <p>I can't think of it. </p>
P粉242535777P粉242535777452 days ago467

reply all(1)I'll reply

  • P粉111627787

    P粉1116277872023-08-19 00:43:36

    To change the onclick event of an image using JavaScript, you need to have an image with an id:

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

    Then, when the image is clicked, you can call the JavaScript function:

    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 when the current img.src is set to minimize.png and vice versa. For more details, please visit: Changing the onclick event link of an image using JavaScript

    reply
    0
  • Cancelreply