Using jQuery to trigger a CSS transformation with a click event

I am facing a challenge where I need to modify an already transforming element when it is clicked. However, the current code does not trigger any action upon clicking.

While utilizing jquery-ui partially resolves the issue by bringing back the element to its original position and then scaling it upon click.

I prefer not to use jquery-ui and would like the previous revolving animation to halt on click, scaling the element at the point where the animation paused.

<html>
    <head>
        <style type="text/css">
            .divInner{
                -webkit-animation: myOrbit 5s linear infinite;
            }

            @-webkit-keyframes myOrbit {
                 from { -webkit-transform: rotate(0deg) translateX(20px) rotate(0deg); }
                 to   { -webkit-transform: rotate(-360deg) translateX(20px) rotate(360deg); }
            }
        </style>
        <script src="jquery-1.11.1.min.js" type="text/javascript"></script>
        <script>
        $(".divInner").click(function() {
            $(this).css('-webkit-transform','scale(1.3)');
        });
        </script>
    </head>
    <body>
        <div class="divOuter" style="padding:20px;">
            <div class="divInner" style="border:1px solid #ddd;width:30px;">
            hello
            </div>
        </div>
    </body>
</html>

Visit this Fiddle link for reference.

Answer №1

To tackle the situation of using only one element, it is essential to obtain the transformation matrix of the element prior to initializing the second animation. Remove the first animation, apply the properties from the saved transformation matrix, and kick off the second animation. This precaution is necessary as an element cannot handle more than one transform simultaneously.

An alternative approach is to implement the effects of the click on the parent instead. By doing so, both the parent and child will be affected proportionally. If desired, a div can act as a direct parent without impacting the layout of the page while avoiding changes to .divOuter.

Answer №2

Check out this jsfiddle link to see a solution: http://jsfiddle.net/H5g5s/22/

This solution addresses the animation freeze and continuation on click by using jQuery for easier manipulation.

Warm regards

HTML:

<div class="divOuter" style="padding:50px;">
<div class="divInner">
hello
</div>
</div>

jQuery:

var interval,//for interval clearance
animation,//for animation freeze
start,//to determine start angle of rotation
duration;//to determine duration of animation

/*** TRANSFORM ANIMATION FUNCTION ***/
function animateDiv(startAngle){

//Determine if animation should continue or start from 0
startAngle ? start = startAngle :  start = 0; 
//Calculate duration for consistent speed
duration = 5000/360 * (360 - start);
//Start animation 
animation = $({deg: start}).animate({deg: 360}, {
    duration: duration,
    easing:'linear',
    queue:false,
    step: function(now) {

        $('.divInner').css({
            '-moz-transform':'rotate(' + -now + 'deg) translateX( 20px ) rotate(' + now   + 'deg)',
            '-webkit-transform':'rotate(' + -now + 'deg) translateX(  20px ) rotate(' + now + 'deg)',
            '-o-transform':'rotate(' + -now + 'deg) translateX( 20px ) rotate(' + now + 'deg)',
            '-ms-transform':'rotate(' + -now + 'deg) translateX( 20px ) rotate(' + now + 'deg)',
            'transform':'rotate(' + -now + 'deg) translateX( 20px ) rotate(' + now + 'deg)'
        });

    }
}); 

}
/*** Call function ***/
animateDiv();
/*** Set interval for repeating ***/
interval = setInterval(function(){
animateDiv();
},5000);

/*** On click ***/
$(".divInner").click(function() { 

/*** Determine action stop or continue ***/
//Stop
if(!$(this).hasClass('active')){

    //Stop interval
    clearInterval(interval);
    //Freeze animation
    animation.stop();
    //Get current style
    var style = $(this).attr('style');
    //Add scale
    var stylescale = style.slice(0,(style.length-1)) + ' scale(1.3)';
    //attach new style
    $(this).attr('style',stylescale);

}
//Continue
else {

   /* get rotation value*/
   var str = $(this).attr('style');
   var rotate = str.search("rotate") + 8;
   var deg = str.search("deg");
   var angle = str.slice(rotate,deg);

   /* start animation again */    
   animateDiv(angle);
   /* sset interval again */
   interval = setInterval(function(){
       animateDiv();
   },5000);  

}

//Toggle class to determine action next time;
$(this).toggleClass('active');

});

CSS:

.divInner{
position:relative;
border:1px solid #ddd;
width:30px;
-moz-transform: rotate(0deg) translateX(20px) rotate(0deg);
-webkit-transform: rotate(0deg) translateX(20px) rotate(0deg);
-o-transform: rotate(0deg) translateX(20px) rotate(0deg);
-ms-transform: rotate(0deg) translateX(20px) rotate(0deg);
transform: rotate(0deg) translateX(20px) rotate(0deg);
cursor:pointer;
}

Answer №3

Give it a shot

HyperText Markup Language

<div class="container" style="padding:20px;position:relative;left:200px;">
<div class="box" style="border:1px solid #ddd;width:35px;">
hello
</div>
</div>

JavaScript

$(".container").click(function() {
    $(".box", this)[0].style.WebkitAnimation = "paused";
    $(this).css('-webkit-transform','scale(1.3)');
});

View the demo on jsfiddle here

Answer №4

Be sure to take a look at this JSFiddle example:

$(".divOuter").click(function() { 
    $(this).toggleClass("pause");  
     $("#divInner").toggleClass("scale");
});

I have set the webkit-animation on OuterDiv and the scale transform on InnerDiv. This setup allows me to stop the animation and apply scaling effects. Interestingly, the first click sometimes does not pause the div as expected, but subsequent clicks work flawlessly.

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

Padding beneath font only seen in Apple devices

My horizontal navigation bar and footer appear perfectly on my PC, but when I tested it on a Mac, the font seemed to be raised about 30px above its intended position in the navigation bar. After attempting various CSS resets and adjustments to the line-he ...

Utilizing CSS to place an image on top of the upcoming <div> container

My goal is to create a layout similar to the one displayed in the linked image. https://i.stack.imgur.com/7DSE9.jpg Currently, I am using Bootstrap 3 and my HTML markup looks like this: <body class="gray-bg"> <section class="white-bg"> <d ...

What is the process of loading a table onto various webpages using HTML?

I am in the process of developing a website to showcase reports in table format, all retrieved from an SQL database using PHP. While the pages are functional, they suffer from slow loading times when dealing with a large amount of data, typically more than ...

What could be causing the color to not appear in the textarea depending on the time condition?

I am attempting to dynamically change the color of my calendar blocks based on the current time. I have created variables for various times in military format and compared them with the current time using a conditional statement. For instance, I have spec ...

The JSONP ajax call encountered an error, throwing a Uncaught ReferenceError stating that jquery19102754115150310099_1392753827782 is not defined

The code snippet below is from an old version of Knockout jsfiddle, which no longer functions due to being outdated in comparison to current versions of knockout and jquery. This particular fiddle was referenced on the Knockout GitHub wiki recipes link: ht ...

Is it possible to create an HTML link that prevents users from navigating back to the previous page or displaying the previous link in their browsing history?

I've been tasked with creating a button on a client's website that links to another page, like Google, for the purpose of assisting someone seeking help in case of an emergency. The challenge is finding a way to prevent the user from easily retur ...

Exploring the distinctions between width/height measurements and the image attribute in styling

What is the benefit of using a style image attribute instead of individually coding width and height for each image? ...

The use of the tooltip function in Rails 6 webpack may not be possible

I have attempted to modify the versions of bootstrap, jquery, and popper without success. I do not believe I am utilizing multiple versions of jquery. I am uncertain as to where the issue may lie. Any assistance in identifying what I may be overlooking wou ...

Sturdy and adaptable in a container designed with a responsive width

Currently, I am developing a responsive app and I am facing the challenge of making some parts of the search bar responsive while keeping others fixed in width (like the search icon). I attempted to achieve this using the following code: .wrapper{ ...

Using requestAnimationFrame to animate several independent objects

I'm currently working on animating two different objects: a square and a circle. Each object has its own button to initiate the animation, which involves moving the object from left to right. However, I've run into an issue where clicking on one ...

Using ServiceStack to deserialize an array

My goal is to post the following data to my ServiceStack web service: $.ajax({ url: 'http://localhost:8092/profiles', type:'POST', data: { FirstName : "John", LastName : "Doe", Categories : [ "Catego ...

Tips for adjusting the width of a table

add your image description hereImagine a scenario where there is a table featuring two columns. <table> <tr><td>Email</td> <td></td></tr> <tr><td>Full name</td> <td></td></tr> ...

What could be causing the discrepancy in alignment of my hyperlink?

I noticed that in this example the hyperlink is aligned at the bottom compared to the text. Can anyone help me identify the issue and provide a solution? Thank you! ...

Using Ajax to fetch project data from an API

Currently immersed in a personal coding project, I'm struggling to troubleshoot my code. Essentially, I need to retrieve data from an API and display it on my HTML page. The data type is "jsonp" due to CORS errors that required this workaround for de ...

Unable to transmit the search query as a parameter

I am working on a dropdown display with autocomplete feature using the select2 jQuery plugin. However, I have encountered an issue where the search term entered in the search box is not being passed as a parameter to the controller method. Here is my curre ...

The transparency feature is malfunctioning in IE9 when using a background

This is a demonstration of a lightbox feature. You can find the code here. When you click on the link "Show Panel," a form will pop out. It works correctly in Firefox but not in IE9. The HTML code is simple: <body> <a id="show-panel" href="#"&g ...

Unexpected Error: Null value prevents accessing 'getElementsByClassName' property in HTML, along with Troubleshooting Inactive Button Behavior in HTML

Can someone identify the error in my HTML code? I keep getting an "Uncaught TypeError: Cannot read property 'getElementsByClassName' of null" error on the second line of the script tag. Additionally, my implemented active header code is not funct ...

Utilizing the .data() method for establishing a variable

I am facing an issue while trying to set a variable in a form using .data(). The problem is that I cannot see any output for the variable "fee" - it just appears blank. What I am trying to achieve is for the user to select a Type, enter a footage, and then ...

Troubleshooting problems with scrolltop offset top

After trying to implement a scroll function to target a specific div on the page, I have encountered an issue. My code includes scrollTop: $(target).offset().top-250 for adjusting the position in the mobile view so that the section appears below the head ...

Span element hides the text in the background

Is there a more efficient way to accomplish this task? My current approach involves creating a slide-in background color effect when hovering over a link. However, I am encountering some difficulties with the CSS implementation. In my setup, each link cont ...