Surprising results when a class is applied using jQuery

Exploring the differences between two fiddles (make sure to run the code on the jsfiddle pages to see the differences clearly).

First Fiddle

Simple demonstration:

$("body").addClass("noScroll");
alert($("body").hasClass("noScroll"));
$("body").removeClass("noScroll");
alert($("body").hasClass("noScroll"));

Accompanied by this css:

.noScroll {
    background-color: pink;
    position: fixed;
    width: 100%;
    top: 200px;
}

In this example, a class is added to the body element, altering its appearance and behavior. The class is then removed, returning the body to its default state. Everything works as expected.

Second Fiddle

$("body").addClass("noScroll");
alert($("body").hasClass("noScroll"));
$(".noScroll").css({
    "background-color" : "pink",
    "position"  : "fixed",
    "width"     : "100%",
    "top"       : "200px"
});
$("body").removeClass("noScroll");
alert($("body").hasClass("noScroll"));

This time, there is no accompanying CSS as it is added through jQuery. Despite similarities to the first example, the CSS is applied but not properly removed. What could be causing this issue?

Thank you!

Answer №1

When the css() function is called on the noScroll selector for the second fiddle, it applies the styles directly to the element with the class noScroll. However, these styles are not saved in a named CSS style.

Essentially, the code is working as intended. It adds the noScroll class, but no specific styles are associated with that class in the CSS. Additionally, when the class is removed, the styles from the css() function call remain because they were applied inline.

For a visual demonstration, you can check out this fiddle where the inline style is manually removed at the end.

Answer №2

Inline styles and CSS classes are distinct ideas. Including or excluding one does not include or exclude the other. Inline styles solely take precedence over styles assigned via classes.

The identifier used to locate the element for applying inline styles is not retained. As a result, jQuery/the browser cannot identify which inline properties to eliminate when the class is removed.

Answer №3

In the second example, you have utilized inline CSS. This can be compared to the following:

<section style="background-color:blue; position:relative; width:50%; bottom:100px;">

...instead of what you initially had in your first example:

<section class="scrollableContent">

As you can see, the removeClass() function is responsible for removing the original class.

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

Trouble with AJAX not properly fetching PHP JSON response

I recently encountered an issue with my jQuery AJAX request that sends user input to a PHP file. Initially, the code worked perfectly fine but adding "dataType: 'json'" caused it to malfunction. Here's how I set it up: $.ajax({ url: url ...

Preserving user interaction history in the browser while syncing with the server in AngularJS

My current challenge involves handling an HTML form that is connected to an object named a through an ngModel. When a user updates the data in the form, I send a PUT request to update the resource on the server. The response from the server contains update ...

Printing Strings in JavaScript IF Conditional Block

Hello there! I am looking for assistance with a JavaScript concept. Recently, I created some code where in the HTML file, there is a div element with an id of "GetID" where the string outputs are meant to be displayed. The JavaScript code looks something ...

Is it possible to run both the frontend and backend on the same port when using vanilla JavaScript for the frontend and Node.js for the backend?

Is it possible to run frontend and backend on the same port in Rest APIs if using vanilla JS for the frontend and Node.js for the backend? I've come across information on how to do this with React, but nothing specific to vanilla JS. Any insights on t ...

Tips for creating a clickable textbox

Does anyone know how to make a textbox clickable even when it is set as readonly. I'm looking for a way to make my textboxes clickable like buttons because I have some future plans for them. <input type="text" readonly value="Click me" id="clickm ...

Vuetify: Dynamic v-select options based on user selection

Here's a codepen I created as an example: https://codepen.io/rasenkantenstein/pen/qBdZepM In this code, the user is required to select a country and then choose cities only from that selected country. The data of people is stored in an array behind t ...

Struggling to showcase API data on React interface

I am working on fetching data from a private API and displaying it on a web page. My frontend is built using React JS, while my backend uses Node with Express and Axios. Everything seems to be working fine until the point where I need to display the fetche ...

Is there a way to change the images displayed in a JavaFXML Button?

I'm attempting to create a button that toggles between displaying an image of a red circle and an image of a blue circle when clicked. In my CSS, I've set up styles for the different states of the button: #button-debit { -fx-background-image ...

What is the best way to send data to an API controller using AJAX in an MVC framework?

I am facing an issue with POSTing a string data to the api controller in mvc using ajax. Despite my efforts, the data does not seem to reach the api controller. Here is what I have attempted: This is the JavaScript code I have used: ...

Troubleshooting issues with JavaScript's window.location.href functionality

Trying to change the URL using window.location.href doesn't seem to be working for a specific link. The current page URL is: http://localhost:37368/Office/Search/c2VhcmNoaWRzPTEyMiwxMjIsMTI0LDE1OCwzNzl8bG9jYXRpb25pZHM9MSwyfGZyb21pZHM9fHRvaWRzPQ== Af ...

Tips for getting the setInterval function to work with a progress bar even when a tab is not in focus

After browsing through similar questions, I couldn't find the answer I was looking for. As a newbie in programming experimenting with JavaScript Progress Bar, I encountered an issue where the progress bar would pause and the counter wouldn't coun ...

Ways to create collapsible navigation bars in your website

As someone exploring client-side development, I may be misusing the term "collapsible" in my title. What I aim to accomplish in my web application is allowing users to collapse header bars into small chevrons and expand them back when necessary. I am on t ...

Once the response is received, the ajax function does not trigger any callbacks such as complete, success,

I am currently facing an issue with an AJAX call to a CakePHP function in the controller. The problem lies in the fact that after the controller function sends back a response, neither the complete nor success nor error functions are being triggered. Any ...

The function SVGGeometryElement.isPointInFill() may not function correctly in Chromium, but it does work properly in Firefox

I'm currently working on a solution to detect when a path within an SVG file on a canvas has been clicked. The code I've written functions correctly in Firefox, but I'm encountering issues with Chromium browsers. When I surround the code wit ...

Retrieving data from the <script> tag and transferring it to the t-esc tag within Odoo 12

After attempting to retrieve the current coordinates of a location in Odoo, I successfully obtained longitude and latitude data through an alert generated by the following code: <button onclick="getLocation()">Try It</button> ...

Tips for aligning 2 columns when both table cells contain inner tables

Concerning my HTML table, cells #3 and #4 contain inner tables. I am facing an issue with aligning the rows within each table in cell #3 and cell #4 properly. Sometimes, the length of text in a row exceeds a single line, causing misalignment with the othe ...

PHP code to insert a advertisement div after every 5 rows of results

Is there a way to dynamically insert a div after every fifth row on a result page? I am currently using a script that displays 15 rows from a database with each pagination. Here is my complete script: <?php $sql = "SELECT COUNT(id) FROM table"; ...

Nesting placeholders is not permitted in i18n

I am attempting to implement Interpolation with Vue3 and vue-i18n version 9.3. However, when I try to pass arguments, I encounter the following error: Message compilation error: Not allowed nest placeholder 1 | Showing {{from}} to {{to}} of {{total}} ent ...

You cannot use the "this" keyword outside of a class body

I am facing an issue with my function, can someone help me? Here is the code: function remove_multi_leg(): void { if (Number($("#search_no_legs").val()) < 2) { return; } const removeId: number = Number($(this).attr("data-number")); const ...

Executing mathematical calculations within a JavaScript object

Can an equation be executed inside an object? For instance: var taxes = { gst: '0.10', }; var prices = { first_key: '437.95', total_key: parseFloat(prices.first_key * taxes.gst).toFixed(2), ....... }, }; Or do I n ...