script that applies a style to newly created elements - javascript

I am writing a tampermonkey script that changes the style of an element whose class starts with "blocked". So i have this code:
var blockedelements = document.querySelectorAll("[class^=blocked]");
var element = blockedelements[0];
element.style.display="none";
for simplicity this is only for the first element but i know how to iterate through each one and this code as it is works. the webapp dynamically creates new elements with this class and i want the script to execute for each newly created element which is what i don't know how to do. I want a pure JS solution, not jquery. Is this what a listener is for? i don't know much about javascript.
I would appreciate any pointers, thanks

Instead of manually changing the display value for every instance of the element, you could use JavaScript to add a page-wide style rule to hide all of them. That way you can let the browser handle applying the rule to both existing and future instances of the element for you.
Rough idea:
var rule = "[class^=blocked] { display: none }";
var styleElement = document.createElement("style");
styleElement.type = "text/css";
if (styleElement.style.cssText) {
styleElement.style.cssText = rule;
} else {
styleElement.appendChild(document.createTextNode(rule));
}
document.getElementsByTagName("head")[0].appendChild(styleElement);

Related

The margins in div of new tab not at all taking effect

Hi I am creating dynamic form in new tab using JavaScript. Margin effects on div are not taking effect. I am neither able to set the margins using class and id in css nor using div.setAttribute. Below is the code.
`
var openWindow = window.open('dynForm.html','_blank','');
var windoc=openWindow.document;
windoc.write("This is dynamic form ");
var div=document.createElement("div");
div.setAttribute("style","border:solid");
div.setAttribute("style","margin-left:1cm");
div.setAttribute("style","margin-right:1cm");
div.setAttribute("style","margin-bottom:1cm");
div.setAttribute("style","margin-top:1cm");
div.setAttribute("style","background-color:lightblue");
`Only background color is taking effect on the new tab. The below screen shot shows how the screen looks irrespective of the values of margin.
Quesstion 2: No class or id attribute in my css is being applied to div.
#myDIV2{
background-color:lightblue;
}
I tried div.id="myDIV2";
I also tried div.setAttribute("id","myDIV2");` I applied the same using class also, but still couldn't find any difference. I do not know why its not working and what went wrong here. Please help
You're overriding the styles every time you call setAttribute, try combining the styles and then set the style attribute only once:
var openWindow = window.open('dynForm.html','_blank','');
var styles= [
"border:solid;",
"margin: 1cm;",
"background-color:lightblue;"
];
var windoc=openWindow.document;
windoc.write("This is dynamic form ");
var end_styles = "";
for (var i=0; i<styles.length;i++) {
end_styles += styles[i];
}
var div=document.createElement("div");
div.setAttribute("style", end_styles);
Note: the fiddle won't work on stackoverflow, I used it because it's easier to format code
This is happening because your all style attribute are getting overridden by previous div.setAttribute and your last attribute div.setAttribute("style","background-color:lightblue"); getting applied. Try to put all styles in one go. div.setAttribute("style","style1:value1;style2:value2;style3:value3;");

How can I change css for every DOM object in the page in SAPUI5

I have a things inspector and this things inspector has two titles. I wan to be able to change the css on this titles and make their font size a bit smaller( default fontSize is 16px and I want to drop it to 12px). I tried to get these titles class and use this method to change their size:
var element = document
.getElementsByClassName("sapUiUx3TVTitleSecond")[1];
element.style.fontSize = '12px';
var element = document
.getElementsByClassName("sapUiUx3TVTitleFirst")[1];
element.style.fontSize = '12px';
it does work and I can see the change but as soon as the page finishes loading ( page loading takes couple of second because it needs to read a json object) title sizes go back to its default.
I dont even know this is a right way to access DOM elements and change their CSS.
Please point me to the right direction of how to change DOM object css in SAPUI5 in general
You could create a new CSS file which you include in your index.html.
Just add the needed selectors with the modified attributes in this custom CSS:
.sapUiUx3TVTitleSecond, .sapUiUx3TVTitleFirst {
font-size : 12px;
}
Edit: if you need to change it programmatically, you could use the addStyleClass("yourStyle") method which is available to every UI element
Execute the script after dom gets completely loaded. Try like this
$("document").ready(function()
{
var element = document
.getElementsByClassName("sapUiUx3TVTitleSecond")[1];
element.style.fontSize = '12px';
var element = document
.getElementsByClassName("sapUiUx3TVTitleFirst")[1];
element.style.fontSize = '12px';
})
$("document").ready(function()
{
$(".sapUiUx3TVTitleSecond").css("font-size","12px");
})

How to dynamically set and modify CSS in JavaScript?

I have some JavaScript code that creates some div elements and it sets their CSS properties.
Because I would like to decouple CSS logic from my JavaScript code and because CSS is easier to read in its own .css file, I would like to set the CSS className of my element and then dynamically inject some values into the defined CSS property.
Here is what I would like to do :
style.css:
.myClass {
width: $insertedFromJS
}
script.js:
var myElement = document.createElement("div");
myElement.className = "myClass";
I want to do something like this but at that point myElement.style.width is empty
myElement.style.width.replaceAll("$insertedFromJS", "400px");
I think my problem here is that after the call to myElement.className = "myClass", the CSS is not yet applied.
If I understand your question properly, it sounds like you're trying to set placeholder text in your css file, and then use javascript to parse out the text with the css value you want to set for that class. You can't do that in the way you're trying to do it. In order to do that, you'd have to grab the content of the CSS file out of the dom, manipulate the text, and then save it back to the DOM. But that's a really overly-complicated way to go about doing something that...
myElement.style.width = "400px";
...can do for you in a couple of seconds. I know it doesn't really address the issue of decoupling css from js, but there's not really a whole lot you can do about that. You're trying to set css dynamically, after all.
Depending on what you're trying to accomplish, you might want to try defining multiple classes and just changing the className property in your js.
Setting the style, might be accomplished defining the inner-page style declaration.
Here is what i mean
var style = document.createElement('style');
style.type = 'text/css';
style.cssText = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementById('someElementId').className = 'cssClass';
However the part of modifying it can be a lot of tricky than you think. Some regex solutions might do a good job. But here is another way, I found.
if (!document.styleSheets) return;
var csses = new Array();
if (document.styleSheets[0].cssRules) // Standards Compliant {
csses = document.styleSheets[0].cssRules;
}
else {
csses = document.styleSheets[0].rules; // IE
}
for (i=0;i<csses.length;i++) {
if ((csses[i].selectorText.toLowerCase()=='.cssClass') || (thecss[i].selectorText.toLowerCase()=='.borders'))
{
thecss[i].style.cssText="color:#000";
}
}
could you use jQuery on this? You could use
$(".class").css("property", val); /* or use the .width property */
There is a jQuery plugin called jQuery Rule,
http://flesler.blogspot.com/2007/11/jqueryrule.html
I tried it to dynamically set some div sizes of a board game. It works in FireFox, not in Chrome. I didn't try IE9.

changing css class model using JavaScript

Is it in any way possible, to change a css class model using JavaScript?
Pseudo code:
function updateClass(className, newData) {
cssInterface.alterClass(className, newData);
}
className being the name of the class, which is supposed to be changed (like ".footer") and newData being the new class content (like border: "1px solid pink;").
The target is, actually, just to save space: I am working with CSS3-animations, so changing one attribute of an element, which is affected by it's class, will terminate the animation of of it - The (in my case) font size won't change anymore. Using different classes will require an entire new set of classes for all affected elements, I'd like to avoid this.
I am not searching for a change via
element.className = "foo";
or
element.style.fontSize = "15pt";
Thanks for your help, guys :)
Here's my function to do this...
function changeCSS(typeAndClass, newRule, newValue) // modify the site CSS (if requred during scaling for smaller screen sizes)
{
var thisCSS=document.styleSheets[0] // get the CSS for the site as an array
var ruleSearch=thisCSS.cssRules? thisCSS.cssRules: thisCSS.rules // work out if the browser uses cssRules or not
for (i=0; i<ruleSearch.length; i++) // for every element in the CSS array
{
if(ruleSearch[i].selectorText==typeAndClass) // find the element that matches the type and class we are looking for
{
var target=ruleSearch[i] // create a variable to hold the specific CSS element
var typeExists = 1;
break; // and stop the loop
}
}
if (typeExists)
{
target.style[newRule] = newValue; // modify the desired class (typeAndClass) element (newRule) with its new value (newValue).
}
else
{
alert(typeAndClass + " does not exist.");
}
}
Called with (example)
changeCSS("div.headerfixed","-moz-transform-origin", "100% 0%");
hope this helps.
See my answer here. To answer your question: Yes, it's possible.
#CSS3: I tried exactly the same in one of my html5 experiments. I created an extra <style> element, and changed its contentText to the CSS class definitions I needed. Of course changing the cssRule object would be much cleaner :-)
As far as I can tell the CSS object model cannot easily tell you whether you already have an existing style rule for a particular class, but you can easily append a new rule for that class and it will override any previous declaration of that style.
I found an example of creating dynamic stylesheets.
You should take a look at dojo, it has some nice features where you can do just that..
require(["dojo/dom-class"], function(domClass){
// Add a class to some node:
domClass.add("someNode", "anewClass");
});
http://dojotoolkit.org/reference-guide/1.7/dojo/addClass.html

How can I undo the setting of element.style properties?

I have an element in my document that has a background color and image set through a regular CSS rule.
When a certain event happens, I want to animate that item, highlighting it (I'm using Scriptaculous, but this question applies to any framework that'll do the same).
new Effect.Highlight(elHighlight, { startcolor: '#ffff99', endcolor: '#ffffff', afterFinish: fnEndOfFadeOut });
The problem i'm facing is that after the animation is done, the element is left with the following style (according to FireBug):
element.style {
background-color:transparent;
background-image:none;
}
Which overrides the CSS rule, since it's set at the element level, so I'm losing the background that the item used to have...
What I'm trying to do is, in the callback function I'm running after the animation is done, set the style properties to a value that'll make them "go away".
var fnEndOfFadeOut = function() {
elHighlight.style.backgroundColor = "xxxxx";
elHighlight.style.backgroundImage = "xxxxx";
}
What I'm trying to figure out is what to put in "xxxx" (or how to do the same thing in a different way).
I tried 'auto', 'inherit', and '' (blank string), and neither worked (I didn't really expect them to work, but I'm clueless here).
I also tried elHighlight.style = ""; which, expectably, threw an exception.
What can I do to overcome this?
I know I can put a span inside the element that I'm highlighting and highlight that span instead, but I'm hoping I'll be able to avoid the extra useless markup.
Chances are you're not setting the style on the correct element. It's probably being set somewhere up the line in a parent node.
elHighlight.style.backgroundColor = "";
elHighlight.style.backgroundImage = "";
You can also remove all the default styling by calling:
elHighlight.style.cssText = "";
In any case, you'll still have to do this on the specific element that is setting these properties, which means you may need to do a recursion on parentNode until you find it.
Try
elHighlight.style.removeProperty('background-color')
elHighlight.style.removeProperty('background-image')
have you tried elHightlight.style.background = "";?
I have a highlighter code on my site and this works
function highlight(id) {
var elements = getElementsByClass("softwareItem");
for (var ix in elements){
elements[ix].style.background = ""; //This clears any previous highlight
}
document.getElementById(id).style.background = "#E7F3FA";
}
An HTML element can have multiple CSS classes. Put your highlight information inside a CSS class. Add this class to your element to highlight it. Remove the class to undo the effect.

Categories

Resources