javascript change css declaration - javascript

I am a beginner with jQuery and understand the use of addClass(), but I often have wondered, instead of adding a class to an element, how about changing what the class means?
so for example I have a table row:
<tr>
<td class="somethingIMayNotWantToSee">A</td>
<td >B</td>
<td >C</td>
</tr>
I realize the common way to do this is .css('display','none');.. but instead is it possible, feasible even to just change
.somethingIMayNotWantToSee{ display:block; }
to
.somethingIMayNotWantToSee{ display:none; }
or is that already set in the system when the page loads.

It is technically possible to use javascript to edit the style properties of any style declaration on the page, unfortunately there has untill recently been very little compatibility between the differing implementations of where, when and how one does this.
If you truly wish to change the CSS of the page in such a way, I recommend you visit the MDN page https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets that contains information on how to use javascript to manipulate the CSSOM

Use document.styleSheets may help you solve this problem. It possible HERE.

The CSSStyleSheet.insertRule() method inserts a new/append style rule into the current style sheet.
We can add/append new rules to our predefined class using the insertRule and addRule (as reqd.) methods as is shown below:
function addCSSRule(sheet, selector, rules,index) {
if(sheet.insertRule) {
sheet.insertRule(selector + "{" + rules + "}", index);
}
else {
sheet.addRule(selector, rules, index);
}
//if -else is used because some browsers don't support insertRule
//and some don't support addRule
}
// we can use it as
addCSSRule(document.styleSheets[0], "header", "float: left",-1);
http://happycodng.blogspot.in/2013/12/add-rule-and-insert-rule-methods-css.html

Related

Silktide cookie consent 3.0.3 conflict with Font Awesome 5.0.2 using CSS Pseudo-elements

There seems to be a bug when using this these 2 libraries together and trying to use CSS Pseudo-elements.
I have created a demo here: http://tappetyclick.com/fontawesomebug/. The text in the anchor which has the pseudo-element disappears and I only see the icon
If I remove the cookie consent plugin code then everything seems to work as expected see http://tappetyclick.com/fontawesomebug/test.htm
Has anyone else seen this issue or know what might be causing it.
I could be massively wrong, this is just a guess.
I think this is happening because cookie consent defines the aria-labelledby attr as cookieconsent:desc but the : is the pseudo element selector, therefor it is trying to find a :desc pseudo selector (which clearly doesn't exist).
You MIGHT be able to stop this error by defining it in jQuery
jQuery.extend(jQuery.expr[':'], {
// add the :desc pseudo-selector to jQuery
desc: function (el, index, selector) {
// stub for now
return false;
}
});
or what ever selector library you may be using.
Thats my best guess at least

Do custom markup tags placed in an HTML document affect the flow and is it possible to parse them with JS? [duplicate]

This question already has answers here:
Is there a way to create your own html tag in HTML5?
(18 answers)
Closed 8 years ago.
Would it be possible to do the following
<body>
<main>
<!-- CONTENT -->
</main>
<foot>
<!-- FOOTER CONTENT -->
</foot>
</body>
if I then wrote some JavaScript that did something along the lines of the following. Please note that I don't want you to write the actual code that goes here. This is just a mockup of the core functionality.
for(elem inside main){
elem.makeItBig();
}
for(elem inside foot){
if(elem is img){
elem.makeItSmall();
}
}
I am aware of this post Is there a way to create your own html tag in HTML5?. But I don't really want to create tags to style them but rather to provide identifying attributes to the DOM which I can hook into using JavaScript. Imagine something kind of like a class, but used in a way that you can stitch lots of PHP generated parts together using these tags.
If you use a made up tag in HTML is it ignored by your browser or will it throw an error.
You can use your own tags as far as I'm aware.
You'd need to do some mucking about to get them to work in older IE browsers.
The more important point is - why on earth would you want to? It wouldn't make your code very maintainable or future-proof. Just use classes on proper elements.
Can you create custom tags? yes. Is it a good idea? not really because your tag may not be recognized by some browsers as a valid html standard. you can check this: http://www.w3.org/MarkUp/html-spec/html-spec_4.html#SEC4.2.1
For custom elements specifications you can look at standards specification for custom elements : http://w3c.github.io/webcomponents/spec/custom/
Although your approach seems nice, just think about changing the size of another group of elements ... you would probably use the same function so why not do this:
var makeItBig = function(elem){...};
for(elem in main){
makeItBig(main[elem]);
}
this way you won't have to create a new method for each element you need to change.
But if you really need it that way you can make it like this:
var makeItBigFunction = function(){var elem = this; ...};
// create new methods
for(elem in main){
main[elem].makeItBig = makeItBigFunction;
}
// make use of them
for(elem in main){
main[elem].makeItBig();
}
Notice that there is a big difference between DOM object's properties (or methods) and HTML attributes.
Read more about it: Properties and Attributes in HTML
Feel free to use HTML5 tags like <content>, <header>, <footer>, <aside> etc.
You can read more about them here: http://www.w3schools.com/html/html5_new_elements.asp in section "New Semantic/Structural Elements". Those should be considered as supported in most modern browsers. Actually, you may use any other custom tags, however their default properties (display, position etc.) may be unpredictable.

jQuery $().css("content") returning the string "normal" in IE9

I'm using the CSS content attribute to pass some values from my LESS stylesheet to JavaScript (to use some colors defined in LESS in Canvas elements).
To make my life easier I decided to place these values in a easy way to parse them in JavaScript.
LESS code:
div#colorChart-critical {
content:'#{critical-highest},#{critical-veryhigh},#{critical-high},#{critical-low},#{critical-medium},#{critical-verylow}';
}
which when compiled brings the following CSS:
div#colorChart-critical6 {
content: '#ff0000,#ff7200,#fffc00,#0000ff,#a200ff,#00ff00';
}
Then I try to read them using jQuery:
$("div#colorChart-critical").css("content").split(",");
The problem is that in IE9 calling $("div#colorChart-critical").css("content") is returning the string "normal" for some reason. Opera, Firefox, Safari and Chrome works fine.
Why does this happen in IE9?
Any work-around this issue on IE9? If not any other CSS atribute I can put random texts in?
I could use something like:
background: url(#ff0000,#ff7200,#fffc00,#0000ff,#a200ff,#00ff00);
But this would generate errors on the console.
It's because content as defined in CSS2.1 doesn't work on elements, only on the :before and :after pseudo-elements. IE9 is simply following the CSS2.1 spec here, which mandates that content on elements be computed to normal, always.
I don't know why other browsers would return the value you have defined, especially considering that .css() makes use of getComputedStyle() on those browsers. If they're implementing CSS2.1 content, then they're violating CSS2.1 by not computing the value to normal. If they're preparing for a late CSS3 implementation, whatever that may be, then it would make sense that they implement it on actual elements somehow... shame on them either way.
Which brings me to another point: if you're not actually trying to use CSS to modify the content of an element, don't use content, even if the fact that it's not defined for use with elements is the reason you're making use of this technique in the first place. You can try assigning those colors to certain classes, creating a hidden element and querying that element's color styles instead.
BoltClock answer shows the cause of my problems. I found a work-around by using the font-family instead of the content CSS property.
My LESS code:
div#colorChart-maincolors {
font-family: '#{colorChart1},#{colorChart2},#{colorChart3},#{colorChart4},#{colorChart5},#{colorChart6}';
}
Which compiled into CSS gives:
div#colorChart-maincolors {
font-family: '#c0392b,#2980b9,#2ecc71,#f1c40f,#ecf0f1,#34495e';
}
The string can be acquired using:
removeQuotes= function(string) {
return string.replace(/^['"]+|\s+|\\|(;\s?})+|['"]$/g, '');
};
removeQuotes($("#colorChart-maincolors").css("font-family")); //add a .split(',') to get the colors as an array
The function removeQuotes is necessary because each browser adds a different kind of quotes into the return of getComputedStyle (and by extension the jQuery .css() method). IE9 adds a double quote, Webkit adds a single quote.
See this post on CSS tricks: http://css-tricks.com/making-sass-talk-to-javascript-with-json/ for more information.
you can use replace(/["']/g, "") to remove extra quotation from string
""string"" will be change to "string"

Javascript: select an image element inside a div

I have a parent div gal1, inside which there can be further divs and content, but only one img element without an id as you can see below. Now I want to use only Javascript (no jQuery) to change the style of this image, using gal1 as argument (because the rest of the structure inside this div may vary, only this one image will always be there somewhere). I couldn't find any other stackoverflow question that addresses exactly my situation.
<div class="gallery-preview" id="gal1">
<div class="gallery-preview-img" id="gal-img1">
<img src="galleries/kevin-carls/Monks.jpg">
</div>
<div class="gallery-preview-text" id="gal-text1">
<span class="gallery-name" href="">Road to India</span><br/>
<span class="artist-name" href="">Kevin Carls</span>
</div>
</div>
Than you can make use of method called getElementsByTagName('img') than you should get image and update it.
document.getElementById(gal1).getElementsByTagName('img');
get the content by using id, and then query images by using getElementsByTagName
function getImages(contentId) {
var content = document.getElementById(contentId);
// only one image, just return an item; or you can return an array
if (content) return document.getElementsByTagName('img')[0];
}
You can insert CSS which may be more efficient if you have to do this in more than this single case.
http://jsfiddle.net/65Ggv/
var style_rules = [];
style_rules.push("#gal1 img { border: 3px solid green; } ");
var style = style_rules.join("\n");
var el=document.createElement("style");
el.appendChild(document.createTextNode(style));
el.type="text/css";
document.head.appendChild(el);
Unless you absolutely need to pick the colors or border sizes dynamically, which I doubt because you are an admitted beginner, stuffing stylesheets in with Javascript is a Rube Goldberg device. It seems nifty to be able to do this, but if your application is important to you, you will regret it. (You might as well use innerHTML to stuff in a stylesheet in that case -- at least it will be faster than making DOM calls.)
Pranay Rana's answer to use getElementsByTagName is the best option if your constraints are actually stable (only one img). Obtain an element reference el, to gal1, using getElementById, then var myimg = el.getElementsByTagName("img") and you are almost done.
If you insist upon funking with the style nodes, you can stuff whatever properties you want into the style property of myimg. It becomes inline style.
Even so, you almost certainly do not need to stuff in novel rules, and changing inline style is often avoidable. It is more predictable and stable to modify the class attribute on myimg, and use a predefined set of style classes for the cases you need to handle. This will give a nice clean separation of the style from the script, and avoid both the in-lining of the style rules and run-time mutilation of the style tree by code injection.

Accessing CSS custom variable with Javascript

I have as the following style in a css file
#galleryImages{
position:absolute;
top:24px;
left:41px;
width:900px;
moving:false;
}
When I try to access it through Javascript, it returns undefined
The external css is correct, it returns other style variables properly as well as the getElementById
alert("External: " + document.styleSheets[0].cssRules[2].style.moving +
"\nInternal: " + document.getElementById("galleryImages").style.moving);
It gives an alert with:
External: Undefined
Internal: Undefined
Is there a way to access a custom CSS variable through javascript?
Thank you in advance
Most (all?) browsers won't load unknown CSS into the DOM, and JavaScript cannot directly access CSS styles directly, only the ones that are loaded into the DOM.
The only way I can think of would be to implement your own CSS parsing JavaScript, but for the mostpart, that would probably be excessive for what you want to do, and a pure JavaScript solution or a class value would better.
e.g. In HTML
<div class="moveable"></div>
Using that example, you could use your JavaScript to get the classname of the element, and if it has the "moveable" class, you know it can move.
EDIT:
In #Anurag's posted link to the Mozilla bug, it is mentioned that unknown CSS properties are to be ignored as part of the CSS 2.1 specification.

Categories