why the js code can't control the css code? - javascript

<script>
var divBgTop=0;
function initDivTop()
{
divBgTop=document.getElementById("divBg").style.pixelTop;
alert(divBgTop);
}
</script>
<style>
.divBgCss
{
position:absolute;
left:100px;
top:100px;
width:100px;
height:100px;
background-color:red;
}
</style>
<body onload="initDivTop()">
<div class="divBgCss" id="divBg"></div>
</body>
the result is always 0. why?

What you're after is the offsetTop:
divBgTop=document.getElementById("divBg").offsetTop;
Without specifying the unit, you will not get 0 but rather something else but not 100 - you better add unit like px so you won't get wrong results when using the code.
Live test case: http://jsfiddle.net/A9Mr2/1/

There is was an error in the CSS. You specify 100, but without a unit. Make it 100px (or another unit, if you wish).
Now the only problem is the used propery. pixelTop apparently won't work, but offsetTop will. This is a property of the element, rather than the style, so you'll need:
getElementById('divBg').offsetTop
[edit: adjustment and addition after question is modified]

the pixelTop property is read-only, all others are read/write.
you can set the pixelTop property..like http://jsfiddle.net/bingjie2680/WJrn6/
update:sorry: write-only

I think the code should be:
divBgTop = document.getElementById("divBg").style.top;
However, this will only read inline styles. To read computed styles you need to... well... read computed styles :)

Related

Changing a css class from javascript [duplicate]

This question already has answers here:
Changing a CSS rule-set from Javascript
(9 answers)
Closed 4 years ago.
I want to set an element's height to window.innerheight but I have to do it in CSS because somehow I don't have access to that element to use javascript to change it's style.
Is there a way to do that? like changing a CSS class in javascript?
I tried this:
document.getElementById('root').style.setProperty('--view-height', window.innerHeight +'px');
and in CSS:
.menu {
height: var(--view-height) !important;
}
and it works but CSS Variables is not supported in older browsers so I can't use that, but I want something similar.
EDIT:
There is many answer yet they all use javascript, i said i CAN NOT USE js to set the element style! i want to do it only by css class style
In modern browsers you can use:
document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyOtherClass');
Although, for accomplishing your specific case, I'd go with לבני מלכה's answer.
Maybe use proper CSS instead:
window.innerHeight +'px' results in the same height as using 100vh. The unit vh means "viewport height" and 100vh is the full height of the inner window.
See: https://developer.mozilla.org/en-US/docs/Web/CSS/length#Viewport-percentage_lengths
Set height in javascript instead use variables
document.getElementById('root').style.height=window.innerHeight +'px';
See example:
document.getElementById('root').style.height=window.innerHeight +'px';
#root{
background-color:red;
}
<div id="root"></div>
To your edit no use js use height:100vh; :
#root{
height:100vh;
background-color:red;
}
<div id="root"></div>
using vh unit is the proper way to do this.. (although Mahboobeh Mohammadi said that it isn't compatible with ios)
height: 100vh; is the full height of the view..
For Normal Js
function addClassById (_id,_class) {
document.getElementById(_id).classList.add(_class);
}
function removeClassById (_id,_class) {
document.getElementById(_id).classList.remove(_class);
}
addClassById("root","newClass")
I advise to you use JQUERY it s very easy to use.
Put this cdn link on your head tag then use it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
//This is for change css
$("#root").css({
"background-color": "yellow",
"font-size": "200%"
});
// This is how to add class
$("#root").addClass('newClass');
// This is how to remove class
$("#root").removeClass('newClass')
I hope it help you.

js how can I get the source css rule in getComputedStyle rule

as we know that with window.getComputedStyle() method we can get the computed styles of specific element. (see https://jsfiddle.net/r7sgpyt5/1/).
My question is,how can we know where the CSSStyleDeclaration in the computed style come from.for example in https://jsfiddle.net/r7sgpyt5/1/ I have define a css rule like:
#element{
color:red;
border:1px solid #999;
margin:10px;
}
if I use getComputedStyle(element,null).getPropertyValue("color") it returns "rgb(255, 0, 0)",but how can I know the property "color" is defined in the css selector "#element".
Thx!
#Tsingbo, as far as I know it's impossible, but you can try window.getMatchedCSSRules in Chrome.

How to get inline z-index style with jQuery?

Following returns 'auto' instead of 10. Why?
<div class="testclass" style="z-index:10"></div>
<script type="text/javascript">
$(function() {
alert($(".testclass").css("z-index"));
});
</script>
http://jsfiddle.net/kEVq7/50/
Apparently, because the div is not positioned. Make this change to your div's style:
<div class="testclass" style="position:absolute; z-index:10"></div>
And you will 10 in the alert.
This makes sense in that the z-index property doesn't apply to a non-positioned element.
By the way, this further appears to be browser-dependent behavior. Your Fiddle reports 10 under Firefox, but auto under Chrome.
z-index can only be assigned to positioned elements. Try adding:
.testclass {
position:relative;
}
The z-index property can only be applied to elements that have the position absolute, relative or fixed. Since the default property is static you are getting the result auto instead of 10
It must be a bug in Chrome, it works in FireFox.
Just try a vanilla approach
$(function() {
console.log($(".testclass").css("z-index"));
console.log($(".testclass")[0].style.zIndex);
});
http://jsfiddle.net/kEVq7/57/
There is little jQuery use in this, getting the style attribute works cross browser.
It's messy, but you can try this jsFiddle solution. it uses .attr() and .substring to find the value. I'm not quite sure why you cant get the inline value.
http://jsfiddle.net/kEVq7/59/
http://jsfiddle.net/kEVq7/63/
here it is working with vanilla javascript
var x = document.querySelector('.testclass').style.zIndex;
alert(x)
Humm. If you want a n answer I think its a bug but the z-index is correctly set
.testclass {
width: 50px;
height: 50px;
background-color: black;
}
see the demo
CSS z-index property always work with absolute as well as relative positioning value. So you must define position:relative or either position:absolute.
Check this demo jsFiddle
HTML
<div class="testclass" style="position:relative; z-index:10;"></div>
jQuery
$(function() {
alert($(".testclass").css("z-index"));
});
But in your case you can use JavaScript for fast execution in compare of j-Query by using querySelector()
Check this demo jsFiddle
HTML
<div class="testclass" style="position:relative; z-index:10;"></div>
JavaScript
alert(document.querySelector('.testclass').style.zIndex);
Hope this both are help you!

Overwrite CSS Using JavaScript / jQuery Permanently

Is it possible to overwrite CSS file permanently using JavaScript / jQuery?
I want to overwrite just 1 or 2 lines though.
Let's say I have this CSS file:
div#box { width:100px; height:100px; }
then, if I apply this kind of JavaScript:
var sheet = document.createElement('style')
sheet.innerHTML = "div#box {width:200px;}";
document.body.appendChild(sheet);
the div only resized as long as the JavaScript is called (dynamically changed by JavaScript)
I want the CSS file would be overwritten like this
div#box {width:100px; height:100px; }
div#box {width:200px; } //CSS added
or more nicely,
div#box {width:200px; height:100px; } //CSS overwritten
What should I do?
Thx :D
To elaborate on what has been said (And mmmshuddup and calchen are correct):
Javascript alters files on the client side until the document is closed. The changes that scripts make are entirely temporary.
However, javascript could technically use ajax to access a perl/ruby/php/python/whatever script hanging out on the server which would take arguments (What the class would be, which element it would be added to) and apply the classes permanently to your documents, or otherwise edit your style documents.
Another solution would be creating and adding classes and then saving those classes as preferences for a user; you'd create a function which looked through an associative array of element id's and their classes that need to be added upon the page being loaded. I suppose you'd use either cookies or preferably a database for this, if you have users at all. I'm just throwing hypotheticals out there.
I'm pretty sure the server-side editing idea is your best option. It would probably be pretty safe to use regex to locate id's and replace them with the new style.
edit: Upon thinking about it, I realized your style finding and replacing function would have to be pretty sophisticated if you ever wanted to do replacements of styles that involved a lot of selectors. There is probably a more elegant solution, but it's not coming to me. I think this would be a serious headache eventually.
CSS cannot be permanently overwritten using only jQuery/JavaScript.
Try below
$(document).ready (function() {
$('div#box').css( {"border": "1px solid #7F9DB9", "width": "200px", "height": "22px"} );
});
Please do needful changes.
Use something like PHP. Otherwise you can modify the css with jQuery.
// for div#box {width:200px; height:100px; }
$('div#box').css({ width: '200px', height: '100px' });
JS can't do this alone, you need the use of a server side language such as PHP, i can make one for you in PHP if you'd like.
If you want to do it on a per page basis you can use a style tag with contenteditable attribute see: http://devgrow.com/html5-contenteditable-attribute/

jQuery change height on overflow

i have a div and its height is fixed to 100px right now.
but its data is not static and a user can add as much data as he wants, i dont want scroll bars and it should get resized to data contained in it(height only) is there any css property to achieve this except than min-height as it doesnot work on IE.
the div may have multiple children and i am thinking to do something that doesnt involve calculating change of height of all children
thanks
height in IE6 is essentially min-height anyway. If you don't have a problem using quick hacks -
div.blah {
_height:100px;
min-height:100px;
}
...otherwise, tuck it in some Conditional Comments so you can sleep at night.
<!--[if IE 6]>
<style type="text/css">div.blah { height:100px; }</style>
<![endif]-->
You can specify height:auto;overflow:visible;. This will make the <div> autosize itself.
overflow:visible; height:100px;
Should work, no?
Check out this plugin: http://james.padolsey.com/javascript/jquery-plugin-autoresize/
Hope I helped.
had to do using jQuery only calculated height of children and set it parent, css hacks dint helped

Categories