Animating an image in an HTML document by clicking a button through jQuery

I am trying to figure out how to make an image move from the left to the right of a page when a button is clicked. I thought the code below would work, but unfortunately, it's not functioning as expected. I'm new to JQuery and could use some guidance.

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/
        jquery.min.js"> </script>
        <script src="//code.jquery.com/jquery-1.9.1.js"></script>
        <script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <script>
        $( "#but2" ).click(function() {
          $( "#vehi1" ).animate({ right:300px }, 500 );
        })
        </script>
    </head>
    <body>
        <div id="homel11">
            <button id="but2"style="top:200px;left:30px;position:fixed">click me</button>
        </div>
        <div id="vehi" ><img id="vehi1" style="left:0px;position:relative;
        top:540px;"src="vehi.png" />
        </div>
    </body>
</html>

Answer №1

It is important to attach an event within the document-ready handler

$(document).ready(function () {
    $("#but2").click(function () {
        $("#vehi1").animate({
            right: 300px
        }, 500);
    });
});

Answer №2

Here is a suggestion to try:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8>
    <title>Effect demo</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

    <style>
      .toggler { width: 500px; height: 200px; position: relative; }
      #but2 { padding: .5em 1em; text-decoration: none; }
      #effect { width: 240px; height: 135px; padding: 0.4em; position: relative; }
      #effect h3 { margin: 0; padding: 0.4em; text-align: center; }
      .ui-effects-transfer { border: 2px dotted gray; }

      .img-class{left:0px;position:relative;top:540px;}
      .btn-class-SO{top:200px;left:30px;position:fixed}
    </style>

    <script>
      $(function() {          
        $( "#but2" ).click(function() {
          $( "#vehi" ).effect("slide", 500);// run the effect
          //Modify the effect name here if desired
          return false;
        });
      });
    </script>
  </head>

  <body>
      <button id="but2"class="btn-class-SO">Click Me</button>
      <div id="vehi" ><img id="vehi1" class="img-class" src="vehi.png" />
      </div>
  </body>
</html> 

Answer №3

One reason why your code may not be functioning is due to the absence of a DOM ready function declaration within the script tag. Make sure to include the following:

$(document).ready(function () {
   // your code..it is correct!
}

It is essential for running jQuery code as without it, the jQuery code will not run.

Answer №4

Many have pointed out the importance of including document ready in your code. Here is a slightly modified version that may help you understand it better:

http://jsfiddle.net/PH3ff/

JavaScript

$(document).ready(function() {
    $("button[data-move]").click(function() {
        $('img.to-move').animate({left: '200px'}, 500);
    });
});

HTML

<img src="http://placehold.it/200x200" class="to-move" />
<button data-move>click me</button>

CSS

.to-move {
    position:absolute;
    left:0;
    top:30px;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for creating a horizontal bar with CSS using the float property

Looking to create a horizontal scroll layout using CSS and floats? Here's my attempt, but I'm not getting the desired result. Flexbox isn't an option as it needs to be supported on IE. Take a look at my code and point out where I might have ...

What is the trick to showing text underneath a font awesome icon?

My HTML code contains font awesome icons, and I'm looking to have text appear below each icon instead of next to it. Currently, the text is displayed midway to the right of each icon. <div class="icons"> <span class="fa-stack f ...

How can you ensure your CSS code is functional across various browsers?

I have been exploring CSS and HTML for about a week now, but I am facing a challenge that has me stuck for the past thirty minutes. The issue lies in adapting this code to work smoothly across different browsers. While it aligns images in a row of four per ...

Struggling to properly center the footer on my Django template

I'm currently facing an issue when attempting to align my footer in the center of my Django template. The specific class for the footer is Pagination. Base HTML: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict ...

What is the best way to adjust the height of a div based on its child content

I've been experimenting with various methods to extend the white background around the title to cover the rest of the content. I've tried using overflow, clear, min-height, max-height, and even the '*' selector but nothing seems to work ...

One way to target a span inside a label element when a checkbox is checked using React Material UI createStyles is by using CSS selectors in combination with

I need help targeting the span element within a checkbox label in order to change its background color when the checkbox is checked. <div className={classes.container}> <input type="checkbox" id="checkboxid" /> <lab ...

jQuery Confusion: The Mystery of Undefined Global Variables

Check out the code snippet below: <script> var vars = {} $("document").ready(function() { vars.var1 = 2; alert(vars.var1); //displays 2; }); alert(vars.var1); //displays undefined </script> What could ...

Utilizing React to highlight buttons that share the same index value upon hover

I have some data in a JavaScript object from a JSON file, where certain entries have a spanid (number) while others do not. I've written React code to highlight buttons with a spanid on hover, but I'm looking for a way to highlight or change the ...

Unexpected token "," in jQuery UI autocomplete error

Using the autocomplete feature works perfectly on my PC. However, I encounter an error when trying to test it on a mobile device. Do I need to utilize jQuery mobile in order for jQuery to function properly on mobile devices? Error message on line 3 of th ...

Ways to showcase JSON data with jQuery

My code displays movie data from a JSON variable and populates it on a dropdown list based on the selected city. I aim to include show timings along with other details from the JSON content. The code snippet is as follows: $(document).ready(function() ...

Prevent jQuery UI dialog from adjusting its position relative to the browser when scrolling

When I launch a jQuery UI dialog, the position of the dialog changes when I scroll the browser. How can I make it remain in the same position relative to the browser window? ...

Error Handling with PHP's die() Command

There seems to be an issue that I am facing with the die() commands. On my website, I have a member registration page which includes a form. The form's action leads to another PHP script. However, when the form is submitted, instead of displaying an a ...

Creating a unique look for unordered list items in a dropdown navigation

I'm currently working on creating a drop-down menu using nested unordered lists. The functionality of the menu is all set, but I'm running into some styling issues. The main link that triggers the drop-down should have a blue background with whit ...

Is it possible to populate a dropdown list prior to launching a jQuery dialog box?

I have created a form that displays multiple links leading to basic documents such as pdf and docs. Each link has an accompanying href link on the right side, which opens a jQuery dialog with details specific to that particular link. These details includ ...

Using Angular JS to dynamically load an HTML template from a directive upon clicking a button

When a link is clicked, I am attempting to load an HTML template. A directive has been created with the templateUrl attribute to load the HTML file. Upon clicking the link, a function is called to append a custom directive "myCustomer" to a pre-existing di ...

Generating a list from JSON entities

I am tasked with creating a specific list format using values from a JSON object. <li> <span class="room">A20</span> <span class="dropin">3</span> <span class="appoint">1</span> <span class="del ...

including a close button when in use and excluding it when not in use

Seeking assistance with removing the "close" icon if it is not active. Here is the code I currently have $("#mason2 li div").click(function() { $(this).parent().hide().appendTo("#mason2").fadeIn(200); $(this).append('<p class="close"& ...

Make sure that the input field and label are aligned side by side in the

Is there a way to arrange the following HTML in the specified layout? <div> <div> <label>Counterparty</label> <input id="paymentsApp-inpt-cpty" ng-model="selectedPaymentCopy.counterparty" ng-required="true" ...

Validating usernames using Jquery's remote method检verifying the username

Struggling with the validation plugin and Laravel 4.2. I've been attempting to use ajax to check the username, but it's not functioning as expected. No matter if the username exists or not, it always appears available. Another problem arises whe ...

Tips for sending data to CSS in Angular

I have an Angular application where I need to calculate the width of an element and store it in a variable called finalposition. Then, I want to move this element to the left by (finalposition)px when hovering over it. How can I achieve this styling effect ...