Animate an image to the right when clicked, then return it to the left with a second click

Seeking help with animating a set of images to move individually 300px right on first click, and then 300px left when clicked again.

I'm currently facing an issue where my code is not working. It could be due to A) syntax errors or B) the images not rendering at 5px as intended.

UPDATE: The corrected code has been added to this fiddle

View Jsfiddle Demo

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <style type="text/css">
        #wrapper {
            width: 80em;
        }

        .image {
            width: 10em;
            height: 10em;   
            display: block;
            position: relative;
            left:5px;
        }
    </style>

    <script type="text/javascript">
    $(document).ready(function() {
        $(".image").click(function() {
            if ($('this').css('left') =='5px') {                    
                $(".image").animate({"right": "300px"},3000);
            else
                $(".image").animate({"left": "300px"},3000);    
            }
        });     
    });     
    </script>
</head>
<body>
    <div id="wrapper">
        <section id="gallery">          
            <img id="avery" class="image" src='images/OAI.jpg' alt= "On Avery Island Album Art">
            <img id="overthesea" class="image" src='images/ITAOTS.jpg' alt="In the Aeroplane Over the Sea album art">   
            <img id="beauty" class="image" src='images/beauty.jpg' alt="Beauty Demo Album Art">
            <img id="everthingIs" class="image" src='images/everythingis.jpg' alt="Eveything Is EP Album Art">
        </section>
    </div>  
</body> 
</html>                 

Answer №1

Check out this code snippet:

$(document).ready(function () {
    $(".image").click(function () {
        var element = $(this);
        if ($(element).css('left') == '5px') {
            console.log("Executing return statement");
            $(element).animate({
                "left": "300px"
            }, 3000);
        } else {
            console.log("Executing alternate animation");
            $(element).animate({
                "left": "5px"
            }, 3000);
        }
    });
});

View the working example on Fiddle.

Answer №2

Remember to update $('this') to $(this), as the element this should always be used without quotation marks.

Best regards.

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

Open the PDF document in a stylish jQuery popup like fancybox or a similar plugin

Can a PDF file be loaded in a popup? I understand that some browsers may require Adobe Reader to view PDFs, but Chrome has its own built-in PDF viewer. ...

Content will be loaded only after the user clicks on the item

On my blog, I have a share button that displays different social media platforms when clicked. However, the page takes longer to load due to fetching data from multiple servers like Facebook and Twitter. Is there a way to use jQuery to make these buttons l ...

Troubles with Flex wrap in CSS3 on iOS 10.3.2 browsers (Chrome and Safari)

Before sending me to other similar questions, keep in mind that I have already gone through them, attempted the solutions, and they are not resolving my issue. The problem I am encountering involves the flexbox layout. I am using the flexbox layout for ce ...

Update the numerical data within a td element using jQuery

Is there a way to use jquery to increase numerical values in a <td> element? I've attempted the following method without success. My goal is to update the value of the td cell by clicking a button with the ID "#increaseNum". Here is the HTML st ...

Employing a lexicon of hexadecimal color code values to harmonize CSS styles

I have a unique requirement where I need to utilize a dictionary of HTML color codes and then apply those colors as styles. It's an interesting challenge! Here is an example of how my color dictionary looks like: const colorCodes = { red: ...

Utilizing the power of THREE.ShaderLib.phong while integrating subsurface scattering within ThreeJS

My mesh utilizes a ShaderMaterial with THREE.ShaderLib.phong uniforms. I have successfully linked the map, bump, and specular maps textures. The code snippet below demonstrates this: defines = {}; defines["USE_MAP"] = ""; defines["USE_BUMPMAP"] = ""; defi ...

Problem with CSS: In Chrome, text fields have 3px additional margin-right

I am facing an issue with the margins of my text fields. Even though I have set a margin-right of 5px for each field, Google Chrome seems to be adding an additional 3-4px automatically. This problem is evident when I dynamically generate more text fields u ...

Why won't the CSS update in Next.js when the local state variable changes on page load?

I seem to be facing an issue with a variable stored in localStorage that changes when using a toggle button. The color changes correctly upon toggling the button, but upon page refresh, it doesn't display the correct color saved in local storage. Eve ...

Dynamic HTML Table with Ajax Click Event Trigger

I have implemented an HTML table that refreshes automatically every 5 seconds and contains some buttons. The issue I am facing is that the event only triggers before the initial refresh. <?php require_once ('UserTableHtm ...

Having trouble with the width of the Material-UI drawer feature

Encountering an issue with the material-ui drawer. I adjusted the width of the drawer container, which led to a problem where the drawer remains slightly inside the page and visible without clicking the button. It seems to be related to the transform attri ...

What is the best way to adjust a map to completely fill the screen?

I am experiencing an issue with my Openlayer map not fitting to full screen automatically. Despite trying various settings, I am unable to resolve this issue. Can anyone suggest what might be causing this problem? Thank you in advance https://i.stack.imgu ...

retrieve the previous value from the scope

Attempting to create a copy of an event before any changes are made in order to implement a cancel button, I stored it in the oldValue variable. However, both the event and oldValue variables appear to be empty because they are executed before the event fa ...

challenges with incorporating data using ajax and jquery

Hey there, I have a set of products displayed in a repeater on my website and I'm looking to add them to the shopping basket. Below is the button code snippet; <asp:Button ID="sepeteEkle" runat="server" Text="EklEPanpa" class="sepetat" data-id=& ...

Collecting data with Selenium as elements load [Python]

Is there a way to scrape only the newly generated items in sequence? I have a dynamic list that loads with scrolling. There are two methods I can use to scrape all generated divs: Scroll to the bottom of the list and then scrape all generated divs. Scroll ...

Encountered an unexpected comma token while attempting to map an array in ReactJS

Can't figure out why I'm getting an error when trying to map an array in React with the following code: const { loading, error, posts } = this.props; return( {posts.map(onePost => ({ <p key={onePost.id}>{onePost.title}&l ...

Capture each touchdown and convert it to currency format

As a novice in the field of JS, I have put in a lot of effort into learning from various sources such as websites, documentation, friends, and other questions on Stack Overflow. However, despite all my efforts, I seem to be stuck at this point. $(docume ...

Using Leaflet to set the view based on a GeoJSON dataset

I am working on incorporating a leaflet.js map with a square shape imported from an external GeoJSON file. I have determined the exact coordinates for the center of the square, and now I need to convert these coordinates in order to pass them correctly t ...

Is there a way to customize jqwidgets jQuery grid cell classes/styles based on row ID and column name?

{ text: 'sell', datafield: 'Sales', width: '3%', columntype: 'button', filterable: false, cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) { return &apos ...

Having trouble sending data through a jQuery AJAX request?

When I make a post request using jQuery AJAX to an ActionResult method, I encounter the following issue: $("#itemTextbox, #itemTextboxNew, #quantity1Textbox").on("keydown", function (e) { if ((e.keyCode == 120){ var GetReportLast5SellAndBuyURL="/Trd/Se ...

CodeIgniter's feature of a dynamically dependent dropdown list

I am facing an issue with implementing three Dynamic Dependent Dropdown Lists in Codeigniter:- The first dropdown represents company names Based on the company selected, I aim to display that particular company's managers in another dropdown The thir ...