Using jquery to rotate images

I have a collection of images that I would like to display one by one with a 3D and 2D rotation effect.

The HTML structure is as follows:

<div><img src="1.jpg"></div>
<div><img src="2.jpg"></div>
<div><img src="3.jpg"></div>

and so on...

My goal is to transition between images by having the previous image flip out while the next image flips in.

I attempted the following code:

To hide an image:

$hide.animate({ 
   transform: 'rotate(180deg)', 
   opacity: 0.1 
},
1500,
'easeInOutBack', 
function () { 
    $(this).hide(); 
});

To show an image:

$show.show().animate({ transform: 'rotate(180deg)', opacity: 1.0 },1500,'easeInOutBack');

However, this code did not work as expected. I am utilizing only jquery and jquery ui.

Answer №1

Instead of animating rotation with jQuery, consider letting CSS handle it for you.

Here's a suggestion:

JavaScript:

$hide.addClass('hide').removeClass('show');
$show.removeClass('hide').addClass('show');

CSS:

.show, .hide{transition:all 0.3s ease;}
.hide{opacity:0.1;transform:rotate(0deg);}
.show{opacity:1;transform:rotate(1800deg);}

Hope this solution works well for you.

UPDATE:

If you prefer using jQuery over CSS, you could try using a plugin like

UPDATE2:

If neither the CSS nor jQuery plugin approach suits your needs, check out this discussion: CSS rotation cross browser with jquery.animate()

"Animating CSS-Transforms directly with jQuery is currently not possible. Consider the following code snippet:"

I have also put together a demonstration on JSFiddle using this method: http://jsfiddle.net/jhcvb2ty/

Answer №2

Simple animations cannot animate CSS properties that are not numeric.

However, you can use the step function in the animate method to make it work.

For example: http://jsfiddle.net/kevalbhatt18/epp06LL3/2/


 $('#box').animate({  transformValue: -180 }, {
    step: function(now,fx) {
      $(this).css('transform','rotatex('+now+'deg)');  
    },
    duration:'slow'
},'linear');


UPDATE:


For updated example: http://jsfiddle.net/kevalbhatt18/u2ptr4jp/4/

If you simply add a div inside a parent span, it will work for all cases.

Note: You only need to know the first class, as shown in this example with the box class. If you reach the last box, it will flip back to the first one.

$("div").click(function() {
    var that = this;
    $(this).animate({
        transformValue: -180
    }, {
        step: function(now, fx) {
            $(this).css('transform', 'rotatey(' + now + 'deg)');
        },
        complete: function() {
            $(that).hide();
            var nextObject = $(that).next()
             var nextClass = nextObject.attr('class')
            console.log($('#parent').children().hasClass(nextClass));
            if ($('#parent').children().hasClass(nextClass)) {
                var flipNext = nextClass;
                console.log("true")
            } else {
                console.log("false")
                var flipNext = "box";
                console.log(flipNext);
            }

            secondFlip(flipNext, that);


        },
        duration: 'slow'
    }, 'linear');


});

function secondFlip(nextID, that) {
    $('.' + nextID).show();
    $('.' + nextID).animate({
        transformValue: 180
    }, {
        step: function(now, fx) {
            $(this).css('transform', 'rotatex(' + now + 'deg)');
        },
        complete: function() {

        },
        duration: 'slow'
    }, 'linear');

}


Update: Issue with rotation has been resolved

Check out this example: http://jsfiddle.net/kevalbhatt18/u2ptr4jp/6/

Final Result:

After several attempts, I finally found a solution.

Witness the solution here: http://jsfiddle.net/kevalbhatt18/oh07zuh0/

Here, I managed to determine the transformation degree.

(function ($) {
    $.fn.rotationDegrees = function () {
        var matrix = this.css("-webkit-transform") || this.css("-moz-transform") || this.css("-ms-transform") || this.css("-o-transform") || this.css("transform");
        if (typeof matrix === 'string' && matrix !== 'none') {
            var values = matrix.split('(')[1].split(')')[0].split(',');
            var a = values[0];
            var b = values[1];
            var angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
        } else {
            var angle = 0;
        }
        return angle;
    };
}(jQuery));

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

Issue with response.split(",")[0] in Internet Explorer

Here is the code snippet I am struggling with: <script> $('#blah').on('click', function(){ $.ajax({ type: 'POST', url: 'ajax.php', data: {"xxx":"yyy", "zzz":"nnn ...

What causes the Invalid Form Body error to appear when using the Discord API?

While developing a Discord bot, I encountered an issue with creating a ping command. The error message received was as follows: (node:37584) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.footer.icon_url: Scheme "flashybot& ...

jQuery validation for various forms with individual submission buttons

I am working on a single-page application that has multiple forms, such as form_1, form_2, etc., each with its own submit button (submit_1, submit_2, etc.). Each form contains records with checkboxes for taking specific actions and there is also a "select ...

The click listener triggers a single time when a render method is nested within it

When I have a click listener on a button that resets the innerHTML of a div with a render method, the listener fires every time I click if I take out the render function. However, if the render function is included, the listener does not fire multiple time ...

Creating a semicircle shape using three.js extrusion

I am trying to create half of an extruded circle using this code, but it only draws a cube. How can I modify it to achieve the desired shape? // Drawing half of an extruded circle var rightfootgeo = new THREE.CubeGeometry(2, 2, 2); for(var i = 0; i < ...

Issue encountered when trying to send an email using Node.js and Express

I've encountered an issue while attempting to send an email upon submitting an HTML form using nodemailer. Every time I click on the submit button, I receive the following error message... TypeError: sendMail is not a function at C:\Users&bso ...

Leverage the power of Bootstrap's col-push and col-pull

Here is the code snippet I am currently working with: <div class="col-md-9 col-md-offset-3"> <div class="row> <div class="col-sm-4 col-sm-push-4"></div> <div class="col-sm-8 col-sm-pull-8"></div> </div> ...

Choose all elements with a specific class name without the need to specify their position in the list

I'm working on adding a function to my WordPress site that will allow me to show/hide page elements with a specific class. For example, I want any elements (such as rows, containers, and text blocks) that have the 'show-hide' class to be hid ...

How to Remove a Child Element in Jquery and Get the Parent Element

I have a simple task at hand - trying to eliminate a child element while retaining the parent. In simpler terms, I need to extract an element that does not include any children with a specific class. Currently, when I attempt: $("#element").clone().fin ...

Empty array is logged by the server after sending a JavaScript variable through post request

When I use console.log(request.body), the terminal displays {} instead of logging the variable ownerSteamId. Here is my code: Server-side JavaScript: const express = require('express'); const app = express(); const bodyParser = require('bod ...

Using the data () method to define Chart.js annotations in Vue.js can cause them to malfunction

I've encountered an issue while incorporating chartjs-plugin-annotations into a Vue.js application We have successfully integrated ChartJS charts into our Vue applications by defining the chart's config within the data () section of the componen ...

How can I make a bootstrap container maximize the available viewport space?

I've come across several similar posts, but none seem to address my particular dilemma. My challenge lies in presenting a table at the end of a bootstrap grid: <div class="container-fluid"> <!-- Various rows with different size ...

Creating an event declaration using Javascript's onclick function

As I was getting ready to add an onclick event to my element in JavaScript, a question popped into my mind regarding the efficiency of these two options: document.getElementById(myid).onclick = function(e){...} or document.body.onclick = fun ...

Resize drop zone with drag and drop functionality

I am using jQuery for dragging and dropping elements, but I am facing an issue. When I resize the drop zone while starting to drag an item, it seems like the previous size of the drop zone is still being used as the space. Is there a way to fix this? ...

Error encountered: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, anticipating either a comma or a semicolon

I encountered this error after making changes to the source of my image. Prior to editing, everything was functioning correctly. Below is my complete code: <?php session_start(); require_once("/home/a9440778/public_html/registration/connect.php"); fu ...

Scrollable Elements

I have successfully implemented the jquery function .scrollable(); to scroll contents from right to left. However, I would like the content to scroll from left to right. Below is the code I am using: ===================For the HTML===================== & ...

Click on a div to smoothly scroll to the top, then automatically scroll to the bottom if already at the top position

I've implemented a JQuery code on my website that allows the page to scroll to the top when clicking on a div with the class of .bottom. The code is working perfectly fine, here it is: function scrollToTop(){ $('.bottom').click(function ...

Tips for choosing elements that are not next to each other in a JavaScript array

If I have an array and want to select non-consecutive elements, such as the second and fifth elements, is there a simple method to do this? For example: a = ["a","b","c","d","e"] a.select_elements([1,4]) // should yield ["b","e"] EDIT: After some reflec ...

Elasticsearch - displaying selected fields for autocomplete suggestions

I am using autocomplete with jQuery AJAX and I want to return specific fields instead of the entire response. My current setup is: curl -X POST 'localhost:9200/music/_suggest?pretty' -d '{ "song-suggest" : { "text" : "n", ...

Adjustable pseudo-elements derived from the size of the element

I have a unique feature in my web application that involves a span element with inner text and additional :before and :after pseudo-elements used as decorative lines on each side of the text. Check out this JSFiddle example to see exactly what I mean. .c ...