简体   繁体   中英

Trying to make an image move whenever clicked, however the .click even only fires the first time clicked

I'm attempting to have an image (#goon) move and become resized whenever clicked. The code works great, however it only works the first time it is clicked. After the first time the image is clicked, clicking the image does noithing.

Here is the Javascript code:

 var random = Math.floor(Math.random()* 750 + 1) var random2 = Math.floor(Math.random() * 200 + 10) $(document).ready(function() { $("#goon").click(function move() { $("#goon").animate({left: random},0) $("#goon").animate({top: random},0) $("#goon").animate({height: random2},0) $("#goon").animate({width: random2},0) }) }); 

Here is the HTML code:

 <!DOCTYPE html> <html> <head> <title>Goon</title> <link rel='stylesheet' href='style.css' type = "text/css"/> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="https://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script> <script type="text/javascript" src="script.js"></script> </head> <body> <div id = "goondiv"> <img src = "goon.jpg" id = "goon"/> </div> </body> </html> 

My sincere apologies if this is a silly question, but I am still fairly new to web development.

Your random values are only computed once, at the start of your script. Your element is animated to the exact same values on every click, the effect only shows the first time.

You should create new values on every click instead.

$(document).ready(function() {
    $("#goon").click(function move() {

        var random = Math.floor(Math.random()*  750 + 1)
        var random2 = Math.floor(Math.random() * 200 + 10)

        $("#goon").animate({left: random},0)
        $("#goon").animate({top: random},0)
        $("#goon").animate({height: random2},0)
        $("#goon").animate({width: random2},0)
    })
});

HTML

<div id = "goondiv">
    <img src = "goon.jpg" id = "goon"/>
</div>

JS

var random = 750;
var random2 = 200;

$("#goon").click(function move() {
    random = Math.floor(Math.random()*  750 + 1)
    random2 = Math.floor(Math.random() * 200 + 10)
    $("#goon").animate({left: random},0)
    $("#goon").animate({top: random},0)
    $("#goon").animate({height: random2},0)
    $("#goon").animate({width: random2},0)
});

Working Example

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM