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

What is the best way to show an image on the screen once a submit button is clicked?

I have a hidden loader-bar gif that I want to display when the user submits a form. Here is the code: <p class="loadingImg" style="display:none;"><img src="/design/styles/_shared/classic-loader.gif" alt="" /></p> Is there a way to ...

Retrieve the id by using the `$` selector

I am trying to achieve the following in my code : <table> @foreach(var foo in Model.List) { <tr> <td><a href="#" class="MnuCustomerSelect" id="@foo.Id">Select</a></td> <td>@foo.Id</td> ...

Error: JSON parsing encountered an issue with token "o" at position 1 while making an ajax request

When I try to make an AJAX call, my code is set up like this: var Data = { name : $('input[name=name]').val(), email : $('input[name=email]').val(), phoneno : $('input[nam ...

When a specific JavaScript function is triggered, the value of an HTML control will reset to its original default value

I have a form with a specific requirement. I need to allow users to input data in a text field and press enter, which should dynamically create new controls like another text field, a dropdown menu, and another text field using jQuery. While the functional ...

Ways to separate information from a database into multiple option tags for a dropdown selection menu

I've been grappling with this problem for weeks - my data is currently listed in one massive option tag, but I need it to be split into multiple option tags. Can anyone help out? (Node.js newbie here) ------------------------------ CODE ------------- ...

generate a customized synopsis for users without storing any data in the database

In order to provide a summary of the user's choices without saving them to the database, I want to display it in a modal that has already been created. Despite finding some sources online, none of them have worked for me so far. Below is my HTML: &l ...

I'm working on a CSS project and my goal is to ensure that all the items are perfectly aligned in a

I have been working on a ReactJS code and I'm struggling to achieve the desired result. Specifically, I am using Material UI tabs and I want them to be aligned in line with an icon. The goal is to have the tabs and the ArrowBackIcon in perfect alignme ...

Designing a charcoal square div featuring a see-through circular element at its center

I'm working on a design concept that involves creating a square div with a transparent circle in the center. The idea is to have an image as the background, with the transparent circle acting like a window through which the background image can be see ...

Notify of a specific value in an array that is retrieved through an AJAX request

I'm currently facing an issue with trying to display the value obtained from an ajax call. The code snippet below is functional in such a way that it will successfully alert the value of 'row' when grid.onClick is triggered. However, I am st ...

Utilizing Font-face and background images in asset-pipeline plugin: A comprehensive guide

I am currently using the asset-pipeline from CodeSleeve to handle my style sheets in my Laravel project. I have successfully downloaded the application.css file, but I have a question: how can I include images and use font-face in this setup? Here is a sn ...

I'm looking for help on creating a three-column table using javascript/jquery. The table should display Product, Price, and Discount (which is calculated at 20%). Can anyone

Check out this code snippet. var items = ["Laptop", "Tablet", "Smartphone", "Headphones", "Camera"]; var costs = [599.99, 299.99, 799.99, 149.99, 499.99]; displayItems = ""; totalCost = 0; for (var j = 0; j < items.length; j++) { displayItems += " ...

Tips on fixing image movement when scrolling and switching resolutions

I am currently working on developing my HTML/CSS portfolio. However, I am facing an issue where the images on the site move around whenever the scroll level or resolution size is changed. I want the images to remain in their respective blocks, displayed at ...

What steps can I take to stop the background image from zooming in modal view?

I noticed something strange happening when I open a modal after clicking on an image on my website. The background image seems to zoom in along with the modal, thanks to a new class called .modal-open added to the body element. This class includes addition ...

Attempting to showcase a pair of unordered lists side by side using the power of flexbox

I am having trouble getting this to display on a single line, no matter what I try. While there may be simpler ways to achieve this without using flexbox, I am eager to learn how to do it using flexbox properties. My desired outcome is to have the first u ...

Tips for Deleting a Certain Element with Its Children from a String Using JQuery

I have a string that contains HTML elements as shown below var div_elements = "<div id=\"pst_body\"><span class=\"quote\">This is the Quoted Text</span>This is the Original Text Within the Div</div>"; I need t ...

Enhanced Bootstrap Carousel with White Background Transitions

Having trouble articulating my issue, so here's a video that should clarify: https://example.com/video I'm using a bootstrap carousel template for a full-width slider. Despite my efforts to remove the white-space transitions, they persist. Am I ...

Is there a way to display a modal before redirecting to the next page after clicking a submit button in a rails application?

In the scenario where I have two models, Employer and Jobs, consider this situation: an Employer creates an account to post a job and provides their phone number. When they fill out a new job posting and click on the post job button (Submit button), I need ...

jQuery scripts fail to load upon returning using the back button

Attempting to create a website similar to GitHub using PJAX. The page functions normally when utilizing PJAX links, but encounters issues when the back button is clicked. While the content loads successfully, the jQuery scripts are not ready. To see this ...

I am a bit confused about how to use jQuery delegate

Is it necessary to create a new delegate function for each ajax action within dynamically loaded content, or can they be consolidated in the success handler? How should delegate functions be organized and when are they required? For instance, clicking the ...

Splitting the text vertically by utilizing a single DOM element

I am searching for a way to split my text vertically, with line breaks so that only one word should be present on each line. Currently, I have achieved this by using separate DIV elements for each word. Is it possible to accomplish the same layout using ...