Nick Davies
Nick Davies

Reputation: 29

Jquery moving a image instead of a button

So im trying to code up a script were if your mouse goes near the image the image will move. Here is my source and live preview. http://jsfiddle.net/9CDtE/4/ Has you can see once you move near the button it moves which is what i want. But now i need to turn the button into a html form and turn the button into a image. Is there any way to do that ? I am no good with jquery.

html

<button>button</button>

js

$(function(){
    $("button").on({
        mouseover:function(){
            $(this).css({
                left:(Math.random()*200)+"px",
                top:(Math.random()*200)+"px",
            });
        }
    });
});

css

button{
    position:absolute;
    top:10px;
    left:10px;
}

I own a pokemon online game. I want to grab a random pokemon from the db ( which i can do) and then have the pokemon change every time the user moves there mouse near it and moves around the page. So there would be a html form with lets say 3 fields a pokemon name a pokemon id and a pokemon image. One page load it will auto grab a random pokemon from the db and fill in these hidden fields in the html form. Which i can do. Once the user moves his mouse near the pokemon/image it will move and then another random pokemon will be grabbed and the html form will change to the new pokemon info. It will keep changing till the user can click on the image which will then submit the form.

Upvotes: 1

Views: 209

Answers (1)

Andr&#233; Catita
Andr&#233; Catita

Reputation: 1323

By the logic of your code above instead of button in your css and selector.

Insert a img with a specific ID.

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

And use cantTouchThis in your code, your selector would like this:

$("#cantTouchThis").on({

But you are using a button and you said wanted an image, it's confusing, however. You can at any point just insert HTML after your button, like:

$("#cantTouchThis").after('<form>.....</form>');

Please elaborate and explain clearly for a better answer.

Tending to your update, something like this is what you want:

$(function(){
    $("#cantTouchThis").on({
        mouseover:function(){
            $(this).css({
                left:(Math.random()*200)+"px",
                top:(Math.random()*200)+"px",
            });
            //Go get PHP via jQuery AJAX
            // Grab data and now update your form, or insert form!
            // Insert new form $('#following_around').html('<form>...</form>');
            // Example change directly the "Pokemon" ID in the form, without the need to completely insert a new form
            $('#following_around #random_id').html(Math.random()*10);
        }
    });
});

Upvotes: 2

Related Questions