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

Insert image using AJAX

I am attempting to use Ajax to dynamically add an <img> element to a div on my webpage. The image's name needs to be fetched from a database. Although I have successfully added the <img> tag to the div and set the correct source (src) att ...

Using jQuery to locate and substitute specific text

Here's a snippet of HTML code I'm working with for posts that have a sneak peek followed by a "Read more" button to reveal additional content. The issue arises when trying to dynamically remove the "[...]" from only the post where the button is c ...

Are there any CSS attribute configurations that I am overlooking?

Reviewing a colleague's CSS file, I stumbled upon an interesting section. They are a skilled CSS designer, so before jumping to conclusions, I wanted to make sure I am not missing something. In the code snippet below, it seems like they are unintenti ...

Steps to send an asynchronous AJAX request to the server-side within the JQuery validation plugin using the addMethod() function

Currently, I am in the process of developing my own framework using the JQuery validation plugin to validate CRUD forms both client-side and server-side. It is crucial that these forms are not static but rather created dynamically using "handlebar.js". Fo ...

Shine a spotlight on elements that match with jQuery using live() or on()

Check out my jsFiddle demonstration where I have created a button that adds elements and provides links to delete these elements. Instead of actually deleting the elements in this example, I want to make it so that hovering over the (remove) link, which is ...

Using Javascript, you can create a function that can disable or enable a text link based on

Here is the code snippet showcasing CSS styles and HTML elements: CSS: .enableLink{ font-family:Verdana, Geneva, sans-serif; font-size:12px; color:#069; padding-right:20px; text-decoration:underline; cursor:pointer; } .disableLink{ display:none; fon ...

jQuery sending a GET request but receiving null parameters in an MVC controller

Currently, I am utilizing jQuery to perform a GET request. The method being called resides in my MVC-4 controller and expects one parameter. After verifying that both my data and the JSON format are valid: { "txid": "051e30921f2886595ad9f22401437f10a ...

Steps for updating the <option> selection in the third <select> menu when the second <select> menu changes, with the second menu being populated by altering the value of the first dropdown through jQuery AJAX

I'm facing a unique situation in my school management project and have been unable to find a solution online. Here's the issue: I have three <select> elements - the first one is for selecting a class, the second one is for selecting a secti ...

Sending an image via email using a highly limited HTML interface

I am working on setting up a webpage connected to my company's internal Intranet page that is specifically designed to allow an iPad to take a picture and then email the picture using our webmail application. The current HTML code I have only allows m ...

The issue persists with json_encode as it fails to display the desired JSON output

<?php include("db_connection.php"); if(isset($_POST['id']) && isset($_POST['id']) != "") { // retrieve User ID $user_id = $_POST['id']; // Retrieve User Details from database $query = "SELECT * FROM prod ...

A step-by-step guide on displaying MySQL data in a text field using AJAX

My understanding of ajax was limited, so I have a question. I am trying to display my wordlist from mysql in an array format within a text field on index.php <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">< ...

Display the contents in a textarea with modal, not as a string

I'm currently working on implementing a modal overlay window with simplemodal that will display the contents of a text area. My goal is to show the rendered output rather than just the string value. For example, if a user enters HTML or includes an im ...

Obtain the checkbox status using node.js

I'm trying to access the checkbox value from req.body in a node.js application. However, when I log it, it keeps showing as 'undefined.' HTML <label> <input name='sell' type='checkbox' value='fals ...

Tips for Deselecting a Table Cell in React

I've been working on a table in React and I'm trying to implement a feature where clicking on a cell colors it, and clicking on another cell uncolors the previous one. So far, I've managed to color cells upon clicking but I'm stuck on h ...

The transparent image is causing the menu item to be hidden underneath it because of z-index complications

Could you please review this jsfillde? <nav role="navigation" class="nav-main"> <ul class="nav nav-pills" id="menu-primary-navigation"> <li class="active menu-home"><a href="/">Home</a></li> <li ...

Combining Data in Django using Ajax with JavaScript and Python Integration

I am in need of assistance understanding a basic ajax call from JavaScript to Python. I have a Python function that takes a simple parameter and returns a result. My goal is to send this parameter from JavaScript, receive the function result back in JavaSc ...

From HTML to Python to Serial with WebIOPi

I am facing a dilemma and seeking help. Thank you in advance for any guidance! My project involves mounting a raspberry pi 2 b+ on an RC Crawler rover, utilizing WebIOPi for the task. However, I am encountering challenges and unable to find useful resourc ...

Utilize text wrapping to ensure a fixed maximum height for content display

I am in need of a div that contains text spanning multiple lines, with both a fixed width and a maximum height. Currently, I have applied the CSS property overflow: hidden;. However, my issue arises when the last line of text exceeds the maximum height of ...

Tips for inserting a button under a div when clicked

I am working on a layout where I have several div cards aligned side by side using the display: inline-block property. What I want to achieve is that when I click on a card, a button is added below the respective div. To accomplish this, I tried using jqu ...

Tips on improving a function that verifies the existence of an image used as a CSS background to output a boolean value

I have encountered a challenge while working on a react file-upload component. The issue at hand is relatively simple - I aim to display an icon corresponding to the file extension for each uploaded file. These icons are loaded through css as background im ...