Jen
Jen

Reputation: 156

Change image within a function onclick

I have this function showing an image moving left and right. Is there a way to create a button in the html page that changes one of those images?

For example, if you click on "tell a joke" happy.png changes to laugh.png?

//fish moves on mouse hover
$(document).ready(function() {  
    $("#swim").mousemove(function (event) {//defines the swim area 
        var fish = $("#fish1");//defines the fish css styles
        var position = fish.position();
        var mousey = event.pageX;

        if (position.left > mousey) {
            $("#fish1").html("<img src='images/happy.png' />");//when swimming left, show left facing fish
        } else {
            $("#fish1").html("<img src='images/happyback.png'/>");//when swimming right, show right facing fish
        }

        $("#fish1").stop().animate({//animates the two images to show animated swimming
            left: event.pageX,
            top: event.pageY
        }, 300);
    });
}); 

Upvotes: 0

Views: 466

Answers (1)

JoeyP
JoeyP

Reputation: 2702

Something like this should work

<button type="button" onclick="$('#fish1').prop('src','images/laugh.png');">tell a joke</button>

Upvotes: 1

Related Questions