The HTML tag on this page I'm working on is in a class that is giving it a top padding of 28px. I need this to go away temporarily when a button is clicked, but it doesn't appear that I can change the styling of the HTML tag itself.
Will I need to use position: relative; on the body tag or something similar? Is there really a way to assign CSS to the HTML tag that I don't know about?
# Comments:
Sorry, I'm in a bit of a rush here. It's something to the effect of this:
<html class='pad_my_top'>
<head>
<style type='text/css'>
.pad_my_top{
padding-top: 28px;
}
body{
background: #000000;
}
</style>
<script type='text/javascript'>
function its_gone(){
// Something here to remove padding.
alert("It's gone. Hurray!");
// Something to put it back.
}
</script>
</html>
<body>
<button onClick='its_gone()'>Click me to get rid of the top padding</button>
</body>
</html>
I really want it gone so I can print the page with Javascript, but I'd rather not use any 3rd party code because this is for a plugin for Wordpress and I don't want a billion dependencies. I only need to hide/re-display 3 divs and (re)change 2 styles.
Use this to remove the top padding:
document.documentElement.style.paddingTop = "0";
and this to set it back:
document.documentElement.style.paddingTop = "28px";
There's no reason to use getElementsByTagName and whatnot...just use document.documentElement. Also, it's better to use a class and toggle that instead of directly setting the style attribute. What if you change the 28px to 20px in your CSS? Then you have to change it somewhere else. Since you are sure you want the top-padding to be 0, then add a class that sets that. When done, remove that class. Like this:
<style type="text/css">
.no-top-padding {
padding: 0 !important;
}
</style>
document.documentElement.className += " no-top-padding";
And to "add" the padding back (by effectively removing the class):
var old_class = document.documentElement.className;
document.documentElement.className = old_class.replace(/(?:^|\s)no-top-padding(?!\S)/g, "");
Although it could be done a lot cleaner with the DOM API classList. The regex is just a safer way for making sure the className property is modified correctly to remove the "no-top-padding" class.
Related
The CSS I'm trying to remove from the iFrame (colours.css in phpbb)
html, body {
color: #536482;
background: url("../path/to/background.jpg") repeat-x #8fe909;
}
The iFrame:
<iframe id="commentframe" scrolling="no" name="commentframe" onload="iframeLoaded()" src="/forum/viewtopic.php?f=13&t=10">
This is also wrapped up in a div named #commentdiv just for easier handling of the span region. Here is also iframe-loaded, though I think it's irrelevant, people often ask for anything related to the code going on
<script type="text/javascript">
function iframeLoaded() {
var iFrameID = document.getElementById('commentframe');
if(iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
}
</script>
As I understand it, I need to use the .has() jquery function to achieve this task by specifying a CSS class somewhere
.commentsbg {
background-color: transparent;
background: transparent;
}
Then the .has function something like this.
<script type="text/javascript">
$("body").has("iframe").addClass('commentsbg');
</script>
I also tried
<script type="text/javascript">
$("commentdiv").has("iframe").addClass('commentsbg');
</script>
as well as trying them in my string of .on('load', function)s. Honestly, I'm just very very confused as to where any of this is supposed to go. Does the js/jquery go in the CSS file (does this ever happen?)... And does the CSS go in colours.css (the original css file of the iframe)? I'm so lost on this one and been at it for quite some time.
There's a few things to comment:
<script type="text/javascript">
$("commentdiv").has("iframe").addClass('commentsbg');
</script>
Here you forgot the identifier or class for your commentDiv, so your function will not work (# for id and . for classes):
$("#commentdiv").has("iframe").addClass('commentsbg');
or
$(".commentdiv").has("iframe").addClass('commentsbg')
However, I think your are not approaching correctly to what you want to achieve. You can act directly to your desired tag.
Afterwards, CSS properties should modify CSS, so it's better to add a class to your <iframe> when it's loaded if you want and change it's properties in your CSS.
Your code is redundant, with background: transparent and with background-color: transparent, it's better to use:
.commentsbg {
background-color: transparent !important;
}
However, you can act directly to your <iframe> in your CSS, adding !important to remove default styles.
To simplify and summary things, you should modify the background of your iframe, firstly in your CSS (adding !important if needed, because JavaScript will load more your website).
If this doesn't work, try adding a class when you need (onload for example) and modify it's CSS.
<!doctype html>
<html>
<head>
<style>
#sample{
width:100px;
height:100px;
background-color:red;
}
.green {
background-color:green;
}
</style>
</head>
<body>
<div id="sample" ></div>
</body>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
window.setTimeout(function(){
$('#sample').addClass("green");
}, 2000);
</script>
<html>
I want to change the background color of the div with id="sample" from red to green in 2 seconds.I added the javasript to add a class with a green background to the div after 2 seconds.But the added class fails to replace the background color of the div element.So is there any solution which can be applied here to change the background color in two seconds.Also i know it is possible,if we add an another class to toggle between the background colors.An another solution will be appreciated.
It's fails because the weight of ID more than the weight of CLASS:
id = 100
class, pseudo-class = 10
element, pseudo-element = 1
You can use id with class:
<body>
<div id="sample" class="red"></div>
</body>
And then toggle from red to green. No need to use !important.
Moreover, if you want to change it with animation, you can use jQuery animate backgroundColor
<!doctype html>
<html>
<head>
<style>
#sample{
width:100px;
height:100px;
/*Remove this from here*/
/*background-color:red;*/
}
.green{
background-color:green;
}
.red{
/*Create a class for red alone*/
background-color:red;
}
</style>
</head>
<body>
<div id="sample" class="red" ></div>
</body>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
window.setTimeout(function(){
// Calling removeClass with no parameters will remove all of the items's classes.
$('#sample').removeClass();
// Now add the class of green
$('#sample').addClass("green");
}, 2000);
</script>
<html>
Cause
The problem is that an id-style is more important (has more 'weight') than a class style, so #sample has higher precedence than .green and the div remains red. There are many rules that dictate which CSS rules have precedence over others. Make sure to read about CSS rule Precedence, so whichever solution you choose, you know why you chose it and what are the consequences.
Fix
There are many ways to fix this, but they all boil down to making sure that the green rule overrules (is equally or more important than) the default red rule.
Solution (Best): Style on classes, not on IDs.
Add a class to the div that indicates what kind of box it is:
<div id="sample" class="samplecontainer"></div>
Now, in the CSS you can easily apply a default style to such elements, and overrule them too:
.samplecontainer {
background-color: red;
}
.samplecontainer.valid,
/* Or just */
.valid
{
background-color: green;
}
Now the CSS doesn't rely on specific elements, but on element definitions. You can say that containers are by default red, and are made green when they become 'valid' (whatever that may mean in this example). This way, you don't rely on ids in the CSS, which prevents very bulky CSS and the undesirable overrule you bumped into.
Note I renamed 'green' to 'valid' to make it more semantic. What if you want to change the border too, or make them blue instead of green? Then you would still need to dig into the JavaScript code, and also change the class names in CSS and possibly fixed style names in HTML and PHP. Or you can just leave the class name 'green' for the blue element, which is very confusing too. So a name describing the type or state (like valid, active, or whatever suits you best) is easier to read and to maintain.
Solution (Sub-optimal): Add Id to the green rule too
Try do change the css like this, so indicate that an element that has id 'sample' and class 'valid' should be green. I think this is quick fix and less optimal compared to the previous one, and your CSS may become bulky if you have many elements that can become green.
#sample.valid{
background-color: green;
}
Solution (Poor): Adding inline style though JavaScript
Instead of adding a class through JavaScript, you can also add inline style. Inline styles (the style attribute), has higher precedence, so adding style="background-color: green" will overrule the color defined in CSS.
$('#sample').css('background-color', 'green');
I wouldn't much prefer this method, since you would have to dig in your JavaScript to change the styling, end it will get really clunkcy when you want to change other properties as well. Each of the solutions above are preferable over this one.
Solution (Poor and risky): Add !important
From CSSTricks: When Using !important is The Right Choice
The unfortunate typical use case goes like this:
WHY IS MY FRAGGLE ROCKING CSS NOT WORKING INTERROBANG
(use !important rule)
OK, now it's working
Then the next guy comes along and tries to
make new changes. He tries to alter some existing CSS rules, but now
his changes aren't behaving how they should....
There are some cases when !important might be the right choice, but it should never be the quick fix for a problem like this, because in the end you'll and up with a CSS that is very hard to maintain, and various !importants will bite each other. Only use it when you have really thought it through.
Change CSS to
.green{
background-color:green !important;
}
DEMO
Please try this one and remove #simple style css
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
window.setTimeout(function(){
$('#sample').css({'background-color':'green'});
}, 2000);
</script>
in the JavaScript you can use just like that
you may find demo
var a;
function function_name() {
a = 1;
setInterval(new_function, 1000);
}
function new_function() {
if (a === 1) {
color = "requred_color";
a = 2;
} else {
color = "another_color";
a = 1;
}
document.body.style.background = color;
}
.green{
background-color:green !important;
}
change your green class like following
.green{
background-color:green !important;
}
Or try
$('#sample').css({background-color:"green"});
i would like to find all classes and ids inside a certain div ! and these css attributes!
Example :
<div class="demo">
<div class="new_class">
<p id="para">This is Demo Paragraph</p>
<a style="background:#ccc">HyperLink</a>
</div>
</div>
<style>
.demo{
height:100px; width:100px; background:#FF0;
}
.new_class{height:40px; width:40px; background:#999;}
#para{color:#E1E1E1;}
</style>
Now The question is that: i would like to find all classes and ids which are used inside demo class ! and Their css values too(which style applying now. ).
I would like to find result as below :
<style>
.demo{
height:100px; width:100px; background:#FF0;
}
.new_class{height:40px; width:40px; background:#999;}
#para{color:#E1E1E1;}
a{background:#ccc;}
</style>
OP, not sure what your purpose is, but in general, this can be useful. I had a project where I needed to embed a fancy template from one site onto a page on a different site with a very different, and conflicting stylesheet. I used some code similar to the following to grab every applied style from the original content, via document.styleSheets, then reapplied them all as inline styles, so I could put it onto the "parent" site without the stylesheets conflicting.
Fiddle
JS
var selector,rule;
var result=[];
var sheets = document.styleSheets;
for (var i in sheets) {
//rules or cssRules, depending on the browser
var rules = sheets[i].rules || sheets[i].cssRules;
//iterate over every css rule in the document
for (var r in rules)
{
selector=rules[r].selectorText;
rule=rules[r].cssText;
//select demo itself, as well as all of its children
$('.demo, .demo *').each(function () {
//console.log($(this),selector);
//for each element, see if it matches the current rule. add if it does
if ($(this).is(selector))
{
result.push(rule);
}
});
}
}
console.log(result);
//result[0] .demo { height: 100px; width: 100px; background: none repeat scroll 0% 0% rgb(255, 255, 0); }
//result[1] .new_class { height: 40px; width: 40px; background: none repeat scroll 0% 0% rgb(153, 153, 153); }
//result[2] #para { color: rgb(225, 225, 225); }
Granted, you will have to tweak this on your own to do things like, removing duplicate styles that would occur if you were to apply this to a larger block of HTML, and for dealing with inline styles (which this does not attempt to do, but you can get them from the style attribute and work from there...), and possibly the computed style, which you can get with getComputedStyle, as indicated by the #Derek's answer. but this should get you started.
To find all existing id, try:
var ids = [];
$(".demo *").each(function(){ this.id && ids.push(this.id); });
console.log(ids);
Do the same thing for class or anything else.
However, to get your expected output, you must first acquire the defined CSS style for each element. Which one should be included? p by default gets margins and paddings. Do you include those too? You will also need to dig into all the CSS declarations just to find the style that are applied, which is almost impossible to do.
For example,
<div class="yellow"></div>
<style>
div.yellow:not(.blue){
background: yellow;
}
</style>
How do you get the background of the <div> tag? .style.background? Nah, it returns "". Well now you will have to reach into the CSS declaration with document.styleSheets to see which one applied. How do you even check if the rule div.yellow:not(.blue) matches your element? Good luck doing that. (There might be libraries that does this kind of thing, or maybe you can even utilize jQuery's internal selector engine with .is, though it will not be the same as in CSS) Another thing you can do is try getComputedStyle. It gives you every single computed styles that aren't even in your declaration. So what you are trying to do is not possible to do. (I don't even know what you are doing something like this.)
I have a reference to a server side JS file that dynamically creates divs on my page. I am trying to override the css that is inline for the divs that are created but I have not been able to do so.
I have tried !important and the style that is created by the JS still trumps everything I do.
When i look at the style in the developer console of chrome it shows element.style as being the style that "won" over my style
I do not have access to edit the JS file on the server.
I place this in my page and it dynamically creates the divs and styles them.
<head>
<style>
#id
{
background-color: blue; !important;
display:block; !important;
}
.class
{
background-color: blue; !important;
}
</style>
</head>
<script src="http://xxx/xxx/xxxxx/xxxx.ashx?blank=xxxx" type="text/javascript" charset="utf-8"></script>
You can create your own javascript to restyle the divs created by the server javascript.
The CSS !important tag does sound like your answer here but sometimes you need to ensure your CSS declaration is specific enough to the element, i.e.:
<div>
<a style="color:#F00;">A Link</a>
</div>
If I apply the below CSS the inline style or #F00 will still win:
div {color:#fff !important;}
But if I am specific with my CSS declaration i.e:
div a {color:#000 !important;} <--Notice the 'a' tag
Then my link will be #000. This does not matter if the link was loaded in with JavaScript or not.
See my JSFiddle Example: http://jsfiddle.net/zqpy0r6c/
More technical info can be found at
When does CSS's !important declaration not work?
The CSS given in the style attribute on an element always wins over the stylesheets. The best option to override this CSS is to edit the style attribute using some JS:
<script>
function clearInlineStyling(element){
element.style= null;
}
</script>
Next you have to watch the html for your script to add new elements, find them and remove their styling. I would suggest JQuery for this.
I'm trying to append a div inside a div and load a JS inside it. I actually want to do what this link is doing, but here the div is already predefined and on top of that JS and CSS files are getting applied to that div, but I need to append a div ad then act it as an odometer. How can I do it?
So here is what I'm trying.
<div id="abc" class="odometer">13</div>
$("#abc").append("<div id = 'odometer' class = 'odometer'><script src='http://github.hubspot.com/odometer/odometer.js'></script> <link rel='stylesheet' href='http://github.hubspot.com/odometer/themes/odometer-theme-car.css' />")
abc.innerHTML = 222456.89;
I'm not getting the required o/p. How can I do that?
The following is written in documentation :
How To Use.
Add the js and a theme file to your page:
Any element with class name "odometer" will automatically be made into an Odometer! When you want to >update the value, simply update it the same way you normally would.
element.innerHTML = 123 // Native, or.
$('.odometer').html(123) // with jQuery
So, just create an HTML structure of your choice and add the .odometer class to the div in which you want to render the odometer it will automatically do that as these guys taking .odometer as a filter to find the source node.
You don't need to actually include the script inside the div include it anywhere inside body and you are good to go.
Here is demo fiddle
i have added borders for more clearity
.odometer {
font-size: 100px;
border: solid 4px green;
}
.outer {
border: solid 4px red;
}