Monday, April 11, 2011

Expand a link to show image without using javascript

Hi. I have a page with some text and links. I want to display image there itself on clicking those links. However, I am bound of not using javascript at all. All I can use is some server side component like PHP. Thanks

From stackoverflow
  • This is entirely possible, but you have to tolerate the fact that when the user clicks on the link, the page will have to reload in order to show the image.

    So, basically, your links will be something like this:

    http://myserver/myscript.php?id=0

    And then your PHP will include an IMG tag for the appropriate image, perhaps like this:

    $id = $_GET['id'];
    echo "<img src='/images/image_$id.jpg'>\n";
    

    If you were able to use Javascript you could have it work without needing to reload the page, but apart from that, doing it with PHP should be fine.

    Rakesh : Can it be done without reloading the page. With Javascript its easy. But I am bound no to use it.
    yoavf : @Rakesh - you cannot use php without reloading the page - unless you use ajax, which is javascript etc...
    kender : Good advice, I'd add some rules for the $id parameter tho.
    Ben : @kender: yes -- good point!
  • Since you stated in a comment that you don't want to reload the page and can't use Ajax, PHP won't help you because it runs on the server. Instead, you can achieve what you want with CSS. Have a look at this simple demo.

    Basically, you put the image inside the link:

    <a href="#img1">link text <img src="..."></a>
    

    and then specify in your CSS something like:

    a img {display:none}
    a:visited img {display:inline}
    

    so the image is hidden by default, but once the user clicks on the link, the image is displayed. If you have several images on your page, you must assign each link a different href anchor:

    <a href="#img1">link text <img src="..."></a>
    <a href="#img2">link text <img src="..."></a>
    

    One potential issue with this approach is that once a user has revealed a particular image, that image will also be revealed by default on that user's subsequent visits to that page unless he clears his browser history. If you want to prevent that from happening, i.e. always hide all images by default, then, for example, your PHP code could generate random href anchors each time.

0 comments:

Post a Comment