Using jQuery to apply CSS with relative percentage values (+=/-=/)

Today, I experimented with using relative values in jQuery's .css() function.

$block.css({'margin-left': '-=100%'});

This resulted in the following style for the div:

<div class="block" style="margin-left: -100px;">

I noticed that jQuery doesn't properly handle percentages, which led me to research the issue. According to the jQuery documentation:

Starting from jQuery 1.6, .css() supports relative values similar to .animate(). Relative values are strings beginning with += or -= to increment or decrement the current value.

A bug related to this has been reported here, but I find it a bit confusing and am unsure how to solve it.

Does anyone know how to modify this code:

$block.css({'margin-left': '-=100%'});

To achieve this result:

<div class="block" style="margin-left: -100%;">

And then progress to:

<div class="block" style="margin-left: -200%;">

And so forth... I understand that this can be accomplished using .animate(), but my goal is to avoid it and utilize pure CSS for hardware acceleration.

Answer №1

They're indicating that the current version is not functioning properly. The latest bug report shows a commit indicating that the issue will likely be resolved in an upcoming release, possibly v1.12 or v2.2.

In the interim, there are three possible solutions:

  1. You can utilize the animate function with a very short duration (in this example, using an inline-block and only 25% for illustrative purposes):

$(".block").animate({'margin-left': '-=25%'}, 10);
.block {
   border: 1px solid black;
   display: inline-block;
}
<div class="block">012345678901234567890123456789</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

  1. Refer to the commit and apply the patch to your jQuery library (or use the latest work-in-progress build).

  2. Determine the element's dimensions and adjust using pixels:

(function() {
        var $block = $(".block");
        $block.css('margin-left', -($block.width() * 0.75));
    })();
.block {
      border: 1px solid black;
      display: inline-block;
    }
<div class="block">012345678901234567890123456789</div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

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

How to overlay text onto an image using CSS

Is there a more efficient way to overlay text on an image without using position: absolute;? Dealing with position: absolute; for different screen sizes isn't the ideal solution for me. I've searched for alternatives, but all I keep finding is th ...

Incorporate a comma after the second or third digit to separate currency values in JavaScript

Is there a way to add commas to currency values at the 3rd or 2nd place depending on the value itself? The desired output format is: 1000 => 1000 10000 => 10,000 210000 => 2,10,000 2010000 => 20,10,000 12010000 => 1,20,10,000 I am currentl ...

An express.js mishap occurred when attempting to process an HTTP POST request using an AJAX client-side, resulting in a

Encountering a 500 Internal Server Error when attempting to send an HTTP POST request from client-side JavaScript using JQuery AJAX in Express.js. The code resides in the p.js file on the client. function dataHandler(conn,data) { var datalol=data; ...

Not certain about the process of linking a JSON object to a specific web address

I'm currently working with a JSON file that contains images, and I am using a loop to display each item in a photo grid on the page. However, I am now looking for a way to assign a specific URL to each of these photos so that they point to different p ...

When using jQuery, the .change() function will only be triggered after the user clicks a button or

Looking for assistance with an unusual issue in my JavaScript/jQuery code. The jQuery .change() function on a simple text input element only triggers when I click somewhere on the page, open the Chrome console, or press a key on the keyboard. It doesn&apo ...

What is the best way to dynamically adjust the size of a Google map on my website automatically

I need assistance with placing a Google map on a webpage along with textboxes in the div below it: <div id="map_area"> <div id="map_canvas"></div> </div> <div id="date_range"> <input type="text" id= ...

Preventing redirection post-AJAX call using jQuery

Currently, I am attempting to implement a basic form submission using AJAX to send data to submit.php for database storage. However, upon submission, the page redirects to submit.php instead of staying on the current page. How can I make it submit without ...

Why is it that vanilla HTML/JS (including React) opts for camelCase in its styling conventions, while CSS does not follow the same pattern

Each type of technology for styling has its own set of conventions when it comes to naming properties, with camelCase and hyphenated-style being the two main options. When applying styles directly to an HTML DOM Node using JavaScript, the syntax would be ...

Press on the menu <li> item to create additional submenus

A group of friends is facing a challenge. They want to create a dropdown sub-menu that appears directly below the selected item when clicking on a link from a menu. So far, they have been able to use ajax to send requests and generate a sub-menu. However, ...

The link in the navigation bar is not functioning correctly

Let me break down the issue I'm facing here. The problem arises with the navigation buttons that have sub-lists nested within them (ul>li>ul). When attempting to click on these buttons, the link does not work unless I specifically click on the t ...

Custom Component in React Bootstrap with Overflowing Column

I am working on a custom toggle dropdown feature in my React application: import React from 'react'; import 'react-datepicker/dist/react-datepicker.css'; const DateRange = props => ( <div className="dropdown artesianDropdo ...

Exploring the process of passing parameters in Material-UI React styled components

Recently, I developed a new component const CategoryDialog = (props) => { const classes = useStyles(); console.log(props); return ( <div> <Dialog fullScreen open={props.dilaogOpenProp} TransitionCompone ...

The min-height attribute of the tooltip functions, but the min-width attribute does

I found a helpful tooltip on this site: I customized it to work with an input element: <div class="tooltip"> <input type="text" placeholder="Name" name="dp_name"> <span>Full name asd as dasd as dasd</span> </div> ...

Display a specific user's div

Upon clicking the link below <a class="end" href="#">End</a> The code will execute, removing a user from a table and displaying a hidden div. The first user in an array is removed, triggering an email to the second user. $("a.end").click(fun ...

Animate with jQuery to swap the positions of two floating divs

Hello, I recently made some updates to the code by adding 2 divs of different sizes. I am trying to achieve a switching animation using CSS floats for these divs. If you'd like to take a look at the current code, please visit - http://jsfiddle.net/jz ...

Expanding a Material UI Accordion does not cause the surrounding content to shift or move

I'm currently designing a User Interface for a web application that allows users to have multiple projects open simultaneously. To achieve this, I decided to use an accordion as the logical component in the left navigation bar. The reason behind this ...

Ensuring the successful execution of all AJAX calls (not just completion)

I've seen this question asked many times about how to trigger a function once all AJAX calls have finished. The typical solution involves using jquery.stop(). However, my situation is unique - I want to display a confirmation banner only after all AJA ...

Possible rewrite: "Unable to use jQuery to add elements to data fetched through AJAX requests."

I am looking to add a button to copy code inside every div that has a class starting with language. The code is functioning properly, however, after attempting to retrieve data from the database using Ajax, the button no longer appears in the div as it did ...

After saving a rich field in Microsoft Sharepoint, I noticed that a new "External Class" was automatically added to my CSS

Although I am new to Sharepoint, I have experience in HTML and CSS. I recently created a mini HTML application that changes the pictures of hyperlinks on hover. It works perfectly when run on a normal browser outside of Sharepoint. However, the issue aris ...

Styling an image with dual attributes using CSS

I'm looking to customize two img classes with different properties. For instance, in my CSS, I want to define: img { padding-left: 15pt; float: right; } and then: img1 { padding-left: 15pt; float: left; } where img1 would serve as a tag fo ...