Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS [Solved] How can I changed image source on "onclick" using css only?

  • This topic is empty.
Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #152696
    Rak_Rin
    Participant

    I have put image in my html, using “img” tag Now I want change another image on click, how can I do this with css only??

    #152699
    jaycrisp
    Participant

    You can only change a background-image on hover/click in CSS. You’ll need to use javascript to change the src of an img tag.

    However, what you’re trying to achieve may be possible without images at all. What sort of effect are you looking for?

    #152700
    Rak_Rin
    Participant

    I want to just change image on click ( like :Active state )

    But here is the problem i have defined img tag in html and trying to change img src only by css.

    I have gone through the web search but none of this related i found

    #152702
    Paulie_D
    Member

    :active will only apply when the mouse is down. As soon as you let go of the mouse, it wouldn’t apply.

    Anyway, in basic terms, you can’t change the image with CSS unless it’s a bg image…and even then it’s a temporary thing related to states.

    Basically, apart from a couple of nasty ‘hacks, clicks require javascript.

    What we really need to understand is WHY does the image need to be changed? A more detailed explanation of your requirements is needed.

    #152704
    jaycrisp
    Participant

    What we really need to understand is WHY does the image need to be changed? A more detailed explanation of your requirements is needed.

    Exactly, that’s what I was trying to get at.

    Is it an actual image, e.g. a photograph?

    Or is it something like a click able button?

    #152705
    dgriesel
    Participant

    As Paulie said, all solutions to this are kind of hacky. Usually they involve hidden checkboxes or radiobuttons and labels which serve as the click handlers.

    Changing the src of an image is not possible afaik.

    I have two possibilities for you:

    Method 1: Using a hidden checkbox – http://codepen.io/anon/pen/EfLxk This allows the user to toggle between the two states.

    Method 2: Using two hidden radio buttons – http://codepen.io/anon/pen/mJlKc Since no label is pointing at the first radio button, this allows only one change.

    However, doing that for multiple images is not really a good idea, as this can easily become a maintenance nightmare. Image urls scattered across html and css…

    #152706
    Rak_Rin
    Participant

    Yes jaycrisp, it is exactly image only, which i have defined in img src =”path” in my html.

    however now I am going with JavaScript code to toggle this image on click.

    Thanks, all of you to confirm it is not possible by CSS.

Viewing 7 posts - 1 through 7 (of 7 total)
  • The forum ‘CSS’ is closed to new topics and replies.