Search code examples
htmlcssimagehrefswap

use image as link, hide/replace it when clicked at the same time


I'm trying to use an image as a link, while swapping it with another image when clicked at the same time. (Basically want to make it look like a button is pressed, once the user clicks on it). Here's my code:

HTML

<a class="button" id="nonpressed" href="..."><img src="images/nonpressed.png"/></a>
<a class="button" id="pressed" href="..."><img src="images/pressed.png"/></a>

CSS

.button {
position: absolute;
top: 540px;
left: 90px;
}

#nonpressed {
z-index: 2;
}

#nonpressed:active {
visibility: hidden;
}

#pressed {
z-index: 1;
}

The problem is that once I get to hide #nonpressed the link isn't working anymore. I tried hide/show and replace with jQuery too but it didn't really help either.. (well maybe I just messed up, since I'm only getting started with web design--). Any ideas on how I could make this work? Thank you very much!!


Solution

  • You do not need to change the entire link if you just want to change the image. It's very easy with using background-image property. So it's CSS only solution ...

    .button {
      display: inline-block;
      width: 100px;
      height: 100px;
      background-image: url(http://lorempixel.com/400/200/sports/1/);
      background-size: 100px 100px;
    }
    
    .button:active {
      background-image: url(http://lorempixel.com/400/200/sports/2/);
    }
    <a class="button" href="#"></a>

    Either way if you want to hide/show the entire (img) link try with display: none; and display: block;. Then you will also need to add a wrapper cause if you click on the item and hide it then it's gone and nothing will know that you still click on it cause you hide it ... does that makes sense? Like so it works:

    .button {
      position: absolute;
      top: 10px;
      left: 10px;
    }
    
    #nonpressed,
    #pressed:active {
      display: none;
    }
    
    .wrap:active #nonpressed {
      display: block;
    }
    <div class="wrap">
    <a class="button" id="nonpressed" href="#"><img src="http://lorempixel.com/400/200/sports/2/"/></a>
    <a class="button" id="pressed" href="#"><img src="http://lorempixel.com/400/200/sports/1/"/></a>
    </div>