user2694771
user2694771

Reputation: 139

display an image only when button is clicked

Just beginning to learn HTML & Javascript. I have the following code, which works. however, because I have have an img tag in my body it is trying to show a place holder for an image before I click the button. How can I stop this.

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Tesco JSONP</title>

    <script type="text/javascript">

        function picture(){ 
        var pic = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg"
        document.getElementById('bigpic').src = pic.replace('90x90', '225x225');

        }


    </script>


</head>

<body>


        <img id="bigpic" src="bigpic" />

    <button onclick="picture()">Enlarge</button>

</body>

</html>

Best wishes.

Upvotes: 6

Views: 104408

Answers (3)

charlie
charlie

Reputation: 44

I like shin solution, i would do the same thing myself. However theres a lot of way to do that, another option is to put a tiny trasparent image as default and then replace like you did to the other one. like this:

<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Tesco JSONP</title>

    <script type="text/javascript">

        function picture(){ 
        var pic = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg"
        document.getElementById('bigpic').src = pic.replace('90x90', '225x225');

        }


    </script>


</head>

<body>

     // tiny trasparent image
    <img id="bigpic" src="https://maps.gstatic.com/mapfiles/markers2/dd-via-transparent.png" alt="" />

    <button onclick="picture()">Enlarge</button>

</body>

</html>

this way no css is needed but like i said before i prefer Shin's solution.

Upvotes: 1

newman
newman

Reputation: 2719

Add style "display:none" to picture tag

<img id="bigpic" src="bigpic" style="display:none;"/>

And in function picture change it for show image

document.getElementById('bigpic').style.display='block';

There is demo: http://jsfiddle.net/eX5kx/

Upvotes: 10

Shin
Shin

Reputation: 189

Use display property in css, try this:

javascript:

function showPicture() {
  var sourceOfPicture = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg";
  var img = document.getElementById('bigpic')
  img.src = sourceOfPicture.replace('90x90', '225x225');
  img.style.display = "block";
} 

html:

<img style="display:none;" id="bigpic" src="bigpic" />
<button onclick="showPicture()">Enlarge</button>

Upvotes: 3

Related Questions