Having trouble making the jQuery "simulate width: calc(100%)" function work properly?

I am utilizing a combination of HTML, CSS, mediaQuery, Javascript, jQuery, and PrimeFaces in my project. One particular css property I want to use is:

calc(100% - 100px)

To handle old browsers that do not support this property, I have implemented a javascript workaround.

In seeking solutions, I came across several relevant questions on Stack Overflow, such as:

  • css width: calc(100% -100px); alternative using jquery

  • Run JavaScript function when the DOM is "ready"?

  • Getting the width and height of a div after it finished loading

A snippet from my code includes:

1.) The JavaScript function in my facelet:

        <ui:define name="search_results">
        <h:outputStylesheet name="primeicons/primeicons.css" library="primefaces"/>
        <h:outputStylesheet library="css" name="results.css" />
        <h:outputScript library="primefaces" name="jquery/jquery.js"/>
        <h:outputScript library="js" name="results.js"/>
        <script>
            // we need to execute the js function after the page load:
            // @see https://stackoverflow.com/questions/8996316/how-to-execute-javascript-after-page-load
            jQuery(document).ready(function() {
                jQuery(document).ready(function() {
                    // twice in document.ready to execute after Primefaces callbacks
                      document.getElementById("homeDetailsPanelId").setAttribute("style","width:583px !important;");
                      var width = document.getElementById("homeDetailsPanelId").style.width;

                      alert (width);
                });
            }); 
        </script>

2.) The HTML and CSS code for the element in question:

 <div id="homeDetailsPanelId" class="col-7">
 <!-- more code here -->
 </div>

3.) My css file:

    @media only screen and (min-width: 1200px) {

    .col-7 {
        width:calc(100% - 395px);
    }

     /* more styles here */
   }

For a minimal working example, visit:

https://github.com/alexmivonwien/pf.css

Upon loading the page in various browsers, the javascript successfully executes and sets the width of the element correctly. However, once the javascript alert() appears and is acknowledged, the browser applies the css from the media query, thus overriding the previously set width through javascript.

How can I ensure my JavaScript overrides the media query in the CSS?

Current outcome displayed here:

https://i.sstatic.net/RvBAO.png

Answer №1

Did you attempt to establish an critical value:

$('#homeDetailsPanelId').css('width', ''); //Delete width
var styles = $('exampleDiv').attr('style');
styles += 'width: ' + width + ' !important;'
$('#homeDetailsPanelId').attr('style', styles);

Answer №2

Perhaps the issue lies in how the IDs and classes are being handled, consider assigning classes in jQuery and IDs in CSS like this:

CSS

    @media only screen and (min-width: 1200px) {
    
    #homeDetailsPanelId {
        width:calc(100% - 395px);
    }
    
     /* more styles here */
   }

Jquery :

   document.getElementByClassName("col-7").setAttribute("style","width:583px !important;");
                    

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

Is there a way to replicate the functionality of $(document).ready for dynamically loaded AJAX content?

$(document).ready(handler) is triggered once the DOM has finished loading. However, if new content containing a $(document).ready(handler) function is added to the page via AJAX, this function will be executed immediately according to the jQuery API. It&ap ...

How to resolve CORS error when using custom request header in Django with JavaScript and redirecting to OPTIONS request?

I am currently working on building an API library using Django. This API will be accessed by javascript, with the Django-API and javascript running on separate servers. The Django API library requires a custom request header from the javascript front end, ...

Guide on integrating Mongoose/Mongodb with node.js for passport authentication

As I venture into building my initial full stack node.js application, I aim to implement passport for authentication. A tutorial I encountered for passport involved storing user information in a users array. Here's a snippet from the passport-config. ...

Exploring the capabilities of automation testing with charts.js and the latest version of Angular

While working on my testing automation for charts.js, I utilized the ngContext object to retrieve data with this code snippet: document.getElementsByTagName('chart-dataset')[0].__ngContext__. However, since upgrading to angular 14, it seems that ...

Can you explain the distinction between incorporating and excluding the keyword "await" in the following code snippets?

Currently, I'm diving into an MDN article that covers async/await. I've grasped the rationale behind using the async keyword preceding functions, yet there's a bit of uncertainty regarding the await keyword. Although I've researched "aw ...

Smoothly transition between the new and existing child elements in a React component with a

Currently, I am utilizing a React component that renders a child element through props.children. The content within this child element varies dynamically. I am looking for the most effective method to smoothly transition (fade out the old element and fad ...

Enhance your ASP .NET Core development with intelligent React props suggestions

Looking to enable intellisense for React props, previously achieved by passing ViewModel to Razor views (.cshtml) using @model namespace.WeatherVM. This allowed easy access to properties like @Model.TemperatureF, with intellisense providing available optio ...

Minimize the width to display a scrollbar

Check out this page: where you'll find the same code snippet displayed twice - once through GitHub Gist embedding and the second using Jekyll's internal syntax highlighter Rouge. I'm currently working on styling the second code snippet to m ...

transform nested object into a flat object using JavaScript

here is the given JSON format: - { "_id": "5c1c4b2defb4ab11f801f30d", "name": "Ray15", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afddced69e9aefc8c2cec6c381ccc0c2">[email protected]</a>" ...

Is there a way to customize the design of the "Browse" button within the HTML file upload control?

I've been searching high and low on the internet for a simple, sleek method to customize the appearance of the Browse button on an HTML <input type=file> element. However, all the solutions I've come across involve hiding controls, placing ...

Invalid Data Pusher for User Information in Next JS

Hello everyone, I've been practicing using Pusher with Next.js but encountered an issue where it's showing Error: Invalid user data: 'presence-channel' and I can't seem to solve it no matter how hard I try. Could someone please he ...

Access-Control-Expose-Headers configuration not being recognized

When setting up my Apache web server configuration, I made sure to include support for two additional headers that are not part of the standard six: Header set Access-Control-Allow-Origin "*" Header set Access-Control-Expose-Headers: Content-Disposition,X ...

The calendar from my datepicker always seems to pop up behind the Card component

When utilizing a Shamsi Calendar within a Material UI Card, I encountered an issue where the calendar appears behind the card. I attempted adjusting the z-index of the Calendar and placing everything inside a div with another z-index, all while ensuring ...

Fluid Design - Extra Spacing at the Bottom with Percent Margin-Top

Currently, I am working on developing a website using only percentages. However, I have encountered an issue with my main content section. I have set a margin-top of 10%, but this is causing excessive spacing at the bottom of the page and resulting in a sc ...

The issue of AngularJS memory leaks

We're facing a memory leak issue in our AngularJS application when switching between different sections. Pinpointing the root cause has been a challenge for us. Our app includes a main controller with a sub controller nested within it. The sub contro ...

How can I redirect to a different URL using Ajax when successful POST request is made?

Here is the code snippet I am working with: $.ajax({ type: "POST", url: "/pro_signup", data: { data: data, key: key }, dataType: "json", success: function (response) { document.getElementById("pu ...

Disconnecting a Metamask Wallet in an Angular application: A Step-by-

I need assistance with disconnecting a Metamask wallet using web3 in Angular. //this is my wallet connection code async connectWallet() { const accounts = await this.ethereum.request({ method: 'eth_requestAccounts', }); this.selectedAddress ...

Exploring JSON data with React Native

When I send a JSON request, I receive a response with JSON objects; { "kind": "youtube#searchListResponse", "etag": "zy8y9DkaOiYwKh0aStoEqOU_knU", "nextPageToken": "CBQQAA", "regionCode": "GB", "pageInfo": { "totalResults": 40, "results ...

Dealing with throwing Exceptions in jest: A guide for developers

I have developed a method that throws an exception when the provided password does not match a regex pattern. I attempted to handle this in Jest. it('Should prevent insertion of a new user if the password doesn't match the regex', async () ...

Pressing a button within an HTML table to retrieve the corresponding value in that row

How can I click a button inside an HTML table, get the value on the same row and pass it to an input field called FullName? Thanks for your help! <td><?php echo $r['signatoryname'] ?></td> <td ...