When attempting to achieve a CSS percent width, the output is given in pixels instead. I am in search of a solution where the percentage remains the same as the

My styling is set as a percentage, like this:

<style>
  #somediv {width:70%}
</style>
<div id="somediv"></div>

jQuery's css() function returns the result in pixels

$(document).ready(function(){
  var css = $("#somediv").css('width');
  console.log(css);
});

Answer №1

I have developed my own custom jQuery plugin to tackle this issue

(function ($) {
     $.fn.customcss= function(property) {

var selector = this.selector;
var cssProperty = property;

var cssValue;
$.each(document.styleSheets, function(sheetIndex, sheet) {
    $.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
        var selectors = rule.selectorText.toLowerCase().split(',');
        $.each(selectors,function(index,value){
            if(value.trim() == selector){
                var cssResult = rule.style.getPropertyValue(cssProperty);
                if(typeof(cssResult != 'undefined') && (cssResult != null)){
                    cssValue = cssResult;

                    }
                }
            }) 
    });
}); 

var inlineStyles = $(selector).prop('style').cssText.split(';')
$.each(inlineStyles,function(index,value){
    var style = value.split(':');
    if(style[0].trim() == cssProperty){
        cssValue = style[1].trim();
        }
    }) 

if(typeof(cssValue) == 'undefined'){
    cssValue = $(selector).css(cssProperty);
    }

return cssValue;

    };
 }(jQuery));

How to use:

$(document).ready(function(){
    var cssValue = $('#somediv').customcss('width');
    console.log(cssValue);
    });

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

Using the result of one function in another function when using async await

I am facing an issue with running a function based on the return value of another function: // in utils.js methods:{ funcOne(){ // do some thing return true } } //in component.vue methods:{ funcTwo(){ let x = this.funcOne() if(x){ ...

Angular: Enhancing View Attribute by Eliminating Extra Spaces

I'm using an ng repeat directive to dynamically set the height in my code. <ul> <li ng-repeat="val in values" height-dir >{{val.a}}</li> </ul> app.directive('heightDir',function(){ return { restrict: ' ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

Dynamic motion of balloons using jquery technology

I am trying to make an image move smoothly inside a div using jQuery and CSS. I have tried rotation and animation, but nothing has worked the way I need it to. <div class="baloon" style="position:fixed;left:0px;top:160px;"> <img id="rot" class="r ...

The identifier is not being used for the HTML element on the mobile browser

Having some issues with CSS priority on my mobile device. The problem is that the CSS id selector push-content is not being applied to the body element. Surprisingly, it works perfectly fine on my PC browser. The code that's not working on mobile dev ...

JavaScript: Exporting and Utilizing a Function within a Model.js File

Coming from a background in PHP OOP development, I am aware that there are various methods to create classes in JavaScript. I require assistance from a JavaScript developer to resolve this particular issue. Here is the situation: I am building an AWS lamb ...

What is the reason behind Chrome removing an SVG image pattern while utilizing jQuery Draggable?

Currently, I am trying to encapsulate an SVG within a draggable div. The SVG contains a shape or path with an image fill on the face. Surprisingly, it displays perfectly and functions flawlessly in Firefox. However, when it comes to Chrome, the dragging op ...

How can I validate HTML input elements within a DIV (a visible wizard step) situated within a FORM?

I recently made a decision to develop a wizard form using HTML 5 (specifically ASP.NET MVC). Below is the structure of my HTML form: @using (Html.BeginForm()) { <div class="wizard-step"> <input type="text" name="firstname" placeholder ...

Reducing Image Size in JavaScript Made Easy

I need help with a project where I want the image to shrink every time it's clicked until it disappears completely. I'm struggling to achieve this, can someone assist me? Here is the HTML code I have: <html lang="en" dir="l ...

Ensuring a radio button is pre-selected by default in React by passing in a prop

Assume I have a React function similar to this function Stars({handleStarClick, starClicked}) { if (starClicked === 3) { document.getElementById('star3').checked = true } return ( <div className="rate"> ...

Unable to retrieve value - angularJS

An AngularJS application has been developed to dynamically display specific values in an HTML table. The table consists of six columns, where three (Work Name, Team Name, Place Name) are fixed statically, and the remaining three columns (Service One, Servi ...

How should the folder structure be set up for dynamic nested routes in Next.js?

I've been reviewing the documentation for Next.js and believe I grasp the concept of dynamic routing using [slug].js, but I am facing difficulty understanding nested dynamic routes in terms of folder organization. If I intend to develop an applicatio ...

Having difficulties with implementing the throw await syntax in an async express handler in Node.js

const express = require("express"); const expressAsyncHandler = require("express-async-handler"); const app = express(); const func = async () => { return false; }; app.get( "/", expressAsyncHandler(async () => ...

Chrome browser exhibits a phenomenon where the Bootstrap modal will erroneously print the same page multiple times based on the

When I open a modal, there's a print button inside it. I've researched solutions provided here and here to enable printing of Bootstrap modals, but I'm encountering a Chrome-specific bug. The issue doesn't occur in Safari, Firefox, or E ...

Javascript problem with closing the browser window in Selenium WebDriver

Here are a couple of inquiries: Firstly: Is there a method to initiate the browser on a specific URL (instead of about:blank) while also setting the history length to 0 when starting on that URL? Secondly: I suspect this question is related to the one me ...

When using CasperJS to capture multiple screenshots, the most recent screenshot will replace all previous ones

Exploring CasperJS has been a great experience for me. Despite my enjoyment, I've encountered an issue with casper.capture() that has me stumped. I've set it up to capture screenshots whenever a test fails and placed it in a separate setup module ...

How to add 1 to the final element in a JavaScript

I'm currently working on a task that involves incrementing the last element in an array using pop() and push(). However, I'm facing an issue where the original values are being retained after I try to increment the popped array. The objective is ...

What is the best way to reduce the size of an image taken from an image sprite rather than a standalone image?

I have an image sprite and I am looking to make a specific part of it appear smaller using CSS. Any recommendations or suggestions? Thank you in advance. ...

Enhance user experience by implementing a feature in AngularJS that highlights anchor

As I am in the process of developing a chat application using Angular, I have encountered an issue with switching between views. One view, named 'chat.html', displays the list of available users while another view, 'chatMessages.html', ...