1

I have to click a html button TWICE to achieve what i need in my project.So i am using a javascript to click the button using click() .But the following script doesnt work for me. Please try this here http://www.w3schools.com/js/tryit.asp?filename=tryjs_lightbulb .

<!DOCTYPE html>
<html>
<body>

<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">

<p>Click the light bulb to turn on/off the light.</p>

 <script>document.getElementById('myImage').click();
        document.getElementById('myImage').click();
  </script>


</body>

<script>
function changeImage() {
     alert(100);
    var image = document.getElementById('myImage');
    if (image.src.match("bulbon")) {
        image.src = "pic_bulboff.gif";
    } else {
        image.src = "pic_bulbon.gif";
    }
}
</script>

</html>

I have tried clicking it only once to just see whether i am going in right direction or not,even that is not working.

1 Answer 1

1

Try this:

<!DOCTYPE html>
<html>
<body>

<img id="myImage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">

<p>Click the light bulb to turn on/off the light.</p>

<script>
// --> Script code should be before closing body tag
function changeImage() {
     alert(100);
    var image = document.getElementById('myImage');
    if (image.src.match("bulbon")) {
        image.src = "pic_bulboff.gif";
    } else {
        image.src = "pic_bulbon.gif";
    }
}
document.getElementById('myImage').click();
</script>

</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.