Avoid replacing CSS properties, instead use jQuery to supplement them

Can anyone help me figure out how to use the jquery .css() function without overwriting existing values, but instead adding additional values to css properties?

For example, I have an element that currently has the css transform:translate(-50%, -50%). I want to use the jQuery .css() function to ADD transform: rotate(90deg), but every time I try it, it just overwrites the original value.

If my explanation is unclear, please take a look at this fiddle for clarification. http://jsfiddle.net/justinbchristensen/mvhwbjLo/1/

In the Fiddle, you'll notice that clicking the button causes the square to lose its initial transformation, slide down, and rotate. However, subsequent clicks only rotate the square because the 'transform:translate' property is not being lost.

I would prefer not to specify the entire transformation in my .css() function like

element.css('transform', 'translate(-50%,-50%) rotate(90deg)'
; I just want to add the rotation to the existing transformation.

Is there a way to achieve this desired outcome?

Answer №1

Due to the nature of transform being a shorthand property, it requires combining values instead of utilizing an incremental method.

An alternative approach would involve fetching the previous value and appending the new one:

View the Updated JsFiddle here

var rotation = 0;
function rotate() {
    rotation += 90;
    var rotationString = 'rotate(' + rotation + 'deg)';
    var prev = $('#square').css('transform');
    $('#square').css('transform', prev + " " + rotationString);
}

Answer №2

Make sure to keep track of the current style before combining:

let rotation = 0;
function rotateObject() {
    rotation += 90;
    let rotationString = 'rotate(' + rotation + 'deg)';
    let currentStyle = $('#square').css('transform');
    $('#square').css('transform', currentStyle +' '+ rotationString);
}

http://jsfiddle.net/abcd1234/

This method is effective, but I wonder if there are alternative approaches.

Answer №3

The reason for why it replaces the value instead of adding to it is simply because of the way cascading in CSS works. When you set a value on the transform property, it can only have one value at a time. Therefore, from the API's perspective, you are essentially replacing the existing value with a new one. In CSS code, this concept can be demonstrated as follows:

#square {
    transform: translate(-50%, -50%);
    transform: rotate(90deg);
}

As illustrated, the second declaration will override the first one.

CSS does not allow for partial or incremental property declarations. Consequently, there is no direct way to add a value to an existing property without discarding the current value.

Basically, when setting a new value, you must include the existing transform within it. By utilizing jQuery for setting the value, you can fetch the current value using the .css() method, append your new transformation, and then apply the combined result, eliminating the need to hardcode the original value:

var currentTransform = $('#square').css('transform');
var rotationString = 'rotate(' + rotation + 'deg)';
var newTransform = currentTransform + ' ' + rotationString;
$('#square').css('transform', newTransform);

An issue that may arise with this approach is that running this code block again will result in currentTransform containing the previous rotation as well. This means that each subsequent execution will continue adding rotations. If this behavior is undesired, additional checks will need to be implemented or, unfortunately, the value will have to be hardcoded.

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

Show two <p>'s next to each other

I am trying to arrange 2 paragraphs side by side. <p class = "firstClass">This is the first paragraph.</p> <p class = "secondClass">This is the second paragraph.</p> Result: This is the first paragraph. This is the second paragra ...

Is there a way to generate bootstrap divs by parsing csv text?

As I am working on a Bootstrap 3 image gallery, I have noticed that there are multiple recurring divs with a similar structure as shown below: <figure class="col-1 picture-item" data-groups='["groupA"]' data-date-created="2018" data-title=" ...

Tips for verifying if an object has been loaded prior to binding it with jQuery

When loading a "stub" file dynamically with jQuery that contains HTML objects, I aim to bind events to the loaded objects after they have finished loading. An example of what my external file may contain: <div id='myDiv'>click me</div& ...

Troubleshooting: Issues with executing a PHP script from jQuery

I found the source code on this website: It's an amazing resource, but I'm facing an issue where my JavaScript doesn't seem to be executing the PHP script... When I set a breakpoint in Chrome's debugger before the penultimate line (}) ...

How to customize field appearance in Django authentication login view by adding a CSS class

I recently started working with Django and came across Django forms when using the django.contrib.auth.views.login view for user authentication. However, I'm struggling to figure out how to add a CSS class to the username and password fields. The doc ...

Tips for showcasing my database in real-time using Php, JavaScript, jQuery and AJAX

Is there a way to display my MySQL database in real-time through AJAX without overloading it with excessive queries? I am currently utilizing jQuery's load function, but I suspect there may be a more efficient method. Can you offer any advice or alter ...

Refreshing Child's Activities

In my scenario, I am displaying data in a child action and utilizing buttons to modify the displayed information. Here is an example of how I am achieving this: Index.cshtml <head> <script type="text/javascript"> $("#RefreshView").on ...

Missing information in input field using JQUERY

I've been attempting to extract a value from an input tag, but all I keep getting is an empty string. Upon inspecting the frame source, it appears as follows: <input type="hidden" name="" class="code_item" value="00-00000159" /> In order to re ...

What causes the circular progress bar to disappear when hovering over the MUI React table?

My goal was to create a table with a CircularProgressBar that changes its background color from orange to dark blue when hovering over the row. However, despite my efforts, I couldn't get it to work as intended. Additionally, I wanted the progressBar ...

A simple guide to viewing a sequential list of loaded stylesheets in Google Chrome

I've been trying to figure out the loading order of CSS stylesheets in Google Chrome, but I'm finding it a bit confusing. Despite my attempts to use Dev Tools -> Network tab -> filter for Stylesheets, I keep getting different results each time I ...

Customizing input tags

Greetings everyone, I have encountered a dilemma : <input type ="file" name ="fileUpload"> I created a file input that shows "choose a file" by default. I'm not too fond of it and would like to make it look more like a button. However, when I ...

When using jQuery to parse JSON, I am unable to make changes to an array

inventory = new Array(); $.getJSON('items.php', function(data){ $.each(data , function(i,jsonData) { inventory[1] = "item"; }); }); alert(inventory[1]); This code is supposed to display the items in the inventory, but it's ...

Implementing a Radial Cursor with a Custom Background Image in JavaScript

I am attempting to implement a radial cursor on a website that features a background image. Currently, I am facing two main issues: The radial cursor works in Chrome but not in Firefox. When using Firefox, I encounter a parsing error related to the "bac ...

Having trouble deciphering mathematical formulas while editing content on ckeditor

While using math formulas in CKEditor, I noticed that when I insert new content via textarea, the formulas are displayed correctly. However, when I go back to edit the content, the text formulas do not display as before. This is the source code I am using ...

What causes the ongoing conflict between prototype and jquery?

I have researched how to effectively load both prototype and jQuery together, but the solutions I found did not resolve my issue. My current setup involves loading jQuery first, followed by this specific file: http:/music.glumbo.com/izzyFeedback.js, and t ...

Inheritance of currentColor in SVG URLs

Seeking the same solution as mentioned in How can an SVG image inherit colors from the HTML document?, specifically when applied to an svg image used as content on a :before pseudo-element. (The intended outcome is for both checkmarks to adopt the red col ...

Unable to execute jQuery - AJAX in PHP

Welcome_page.php <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#role").on("change", function() { alert($("#role").val()); var rol ...

The HTML attribute "hasbox" specifies the presence of a box within the element

I am currently working on resolving some rendering issues specifically in IE9 and have encountered a tag attribute that I am not familiar with - hasbox. Upon further investigation, it seems like IE is injecting this attribute at runtime as it does not app ...

Transitioning Between Div Elements Using Jquery

I am stuck with the following HTML code: <section> <div id="first"> ---content </div> <div id="second"> ---content </div> </section> When the page loads, the second div and its contents are not visible (I'm uns ...

Styling a modal popup using session storage in CSS

I recently created a modal popup using CSS by following a helpful tutorial that can be found at this link: Now, I am curious about how to store the value entered in a textbox as session data. I came across some code in another tutorial that demonstrated h ...