My webpage has a random CSS function that's working fine:
<link rel="stylesheet" href="/css/<?php echo(mt_rand(1,7));?>.css" />
But I would like to have text display based on which CSS file is selected. Each one has a name associated with it, so for the "Copenhagen" CSS sheet I want it to display the text, "This stylesheet is called Copenhagen."
Right now I'm trying to output text based on the background-color of .skills-title, which for now is either black, white, or everything else ("Fail"). However it's not outputting anything at all. I think it's because the stylesheet is randomized so I can't call a specific stylesheet into the code.
var color = $('.skills-title').css('background-color');
if (color == 'rgb(255, 255, 255)') {
document.write("Copenhagen");
} else if (color == 'rgb(0, 0, 0)') {
document.write("Paris");
} else {
document.write("Fail");
}
After playing around with a lot of different code for a few hours, I feel stuck.
You could try to set an id or title to your Link tag, so you could get it in vanilla js as follow:
// supposing you created it like: <link id="mylink" title="mylinktitle" rel="stylesheet" href="/css/<?php echo(mt_rand(1,7));?>.css" />
let element = document.querySelector("link[title=mylinktitle]")
// or
let element = document.getElementById("mylink");
With element object you could check anything and display the name you want.
Alternatively you could try to send the name in title and use an static id, so you get the element based on some id and display the title associated
Related
I have a svg file that contains some css classes in this format
<style type="text/css" id="style1">
<![CDATA[
.fill1 {fill:#D2D3D5}
.fill2 {fill:#A9ABAE}
.fill3 {fill:#96989A}
]]>
</style>
The svg file is displayed in an HTML file by using the following tag.
<object id="testObject" type="image/svg+xml" data="img/test.svg"></object>
Is there some way for me to get fill value of fill1,fill2 and fill3 using javascript or jquery. Also would it be possible to change these fill colors?
With generic Javascript, you can obtain the CSSStyleSheet object and manipulate any individual CSSStyleDeclaration:
// obtain document of object
var objectDoc = document.getElementById('testObject').contentDocument;
// obtain stylesheet
var stylesheet = objectDoc.getElementById('style1').sheet;
// find a certain rule
var rule2 = Array.from(stylesheet.cssRules).find(function (rule) {
// make sure you reference a style rule and identify by selector string
return rule.type === CSSRule.STYLE_RULE && rule.selectorText === '.fill2';
});
// get fill value
rule2.style.getPropertyValue('fill');
// set a different fill
rule2.style.setProperty('fill', '#676869');
I have an HTML document with a link tag in its head to a particular CSS stylesheet:
<link rel="stylesheet" href="style.css" type="text/css">
This .css file contains a particular class, like so:
.mystyle {
color: #00c;
}
What I'm trying to do is to grab that class's color field, so that I can use it dynamically in another part of the page (for another element's background-color). Is there any way in a JavaScript program to access that information, by the name of the class? Something like this:
var myColor = document.getStyle(".mystyle").color;
Some caveats:
There may or may not be other stylesheets that are also linked from this HTML document.
There may or may not be any particular elements on the page that are styled with this particular class.
I've already tried setting a temporary element to have the given class, and then grabbing its color field. That didn't work: the color field contains the empty string.
Thanks.
You can get all stylesheet information using the StyleSheetList and related objects.
In the example below, I aggregate all the document's styles (i.e., inline styles, an external bootstrap stylesheet and the stylesheet provided by Stackoverflow), and retrieve the color information for the .mystyle class:
const sheets = [...document.styleSheets];
const rules = sheets.reduce((a, v) => [...a, ...v.cssRules || []], []);
const rule = rules.find(r => r.selectorText === '.mystyle');
console.log(rule.style.color);
.mystyle {
color: #00c;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
It's possible to use JavaScript to read the actual CSS files themselves by scraping the DOM and extracting the relevant information. While possible, it's clunky, and I'd advise against that unless absolutely necessary. If it's required, this answer covers it pretty well.
As an alternative to scraping the header information, you could use HTMLElement.style and grab the color value, though note that this will only work for inline styles:
var span1 = document.getElementsByTagName('span')[0];
var span2 = document.getElementsByTagName('span')[1];
// Empty
console.log(span1.style.color);
// Blue
console.log(span2.style.color);
.mystyle {
color: #00c;
}
<span class="mystyle">Text</span>
<span style="color: #00c;">Text</span>
However, a much better solution would be making use of what are known as CSS variables. These are defined in :root with a double hyphen prefix, and can be referenced with var(). This allows you to only set a colour once, and re-use it for both a color property and a background-color property, as can be seen in the following:
:root {
--colour: #00c;
}
.a {
color: var(--colour);
}
.b {
background-color: var(--colour);
}
<span class="a">Text</span>
<span class="b">Text</span>
Hope this helps! :)
Try window.getComputedStyle in combination with getPropertyValue.
var elem = document.getElementsByClassName("mystyle");
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("color");
More: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
For any who might come after me:
One can indeed use window.getComputedStyle(element) on an element. However, creating your own element first (if one doesn't exist) comes with an important caveat. Firefox will properly calculate the computed style. However, Chrome (and possibly Safari too) won't calculate the style of an orphaned element that isn't part of the DOM tree. So if you go that route, be sure to add it to the tree somewhere, possibly as a hidden element.
I need some JavaScript to find the default link color of a page. How do I do it? I looked around but not sure how to do it. I believe jQuery has a .css function I can use but how about regular JavaScript?
Please note I don't have any specific element to target to grab css from, i.e. I can't look for the a color value for #myID -- I need to find the default a color value for the links on the page.
Thanks!
Try: Just place an <a> at the top of your page. This will get the values from the first <a> element.
Without any pseudo elements
window.getComputedStyle(document.body.getElementsByTagName('a')[0], null).getPropertyValue("color");
active
window.getComputedStyle(document.body.getElementsByTagName('a')[0], ':active').getPropertyValue("color");
hover
window.getComputedStyle(document.body.getElementsByTagName('a')[0], ':hover').getPropertyValue("color");
If you have any fears, just go with:
var el = document.createElement('a'); // Creates <a>
document.body.appendChild(el);
var COLOR = window.getComputedStyle(el).getPropertyValue("color");
document.body.removeChild(el);
You can create an element and add it to html, then get the CSS properties of the element that is assigned by default. Example:
var element = document.createElement('a');
document.documentElement.appendChild(element);
var color = getComputedStyle(element).color;
console.log(color) //rgb(0, 119, 204) stackoverflow default link color
Try this on StackOverflow page, opening the console.
Demo
I converted xlms file to HTML file to embed it to my web page, but some conditional tags were not working, So I am trying to handle it using CSS/Javascript on HTML file.
I have column called status, In this column-cells, if the value is 1/2/3, I want to show it with various coloured bullets. (I will use background image in CSS(td)).
But the problem is td(which has no specific ID only css class), I want to get value in that td and according to value I will put background image. Code part which is generated for that cell is like below:
<td class=xl21627 style='border-left:none'>3.00</td>
How can I access all cells and change background of this cells based on value inside it.
If all the target td's has the same class
jQuery(function ($) {
var imgs = {
1: '//placehold.it/32/ff0000',
2: '//placehold.it/32/00ff00',
3: '//placehold.it/32/0000ff'
}
$('.xl21627').css('background-image', function () {
return 'url(' + imgs[parseInt(this.innerHTML)] + ')'
})
})
Demo: Fiddle
Couldn't find a punctual answer for this simple task and your help is highly appreciated
We have an image we want to switch based on user's color selection.
Tried several methods, none worked.
This is the idea:
$('#YourButton').click(function() {
var oldSrc = 'images/Image1.png';
var newSrc = 'images/Image2.png';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
});
Just change the image source with javascript by clicking your button with another color
Note: it´s jquery so you have to include the js file..
Just bind a click listener to your button and change the src attribute of your image.
$('#colorButton').click( function() { //choose a new color
$('#imageIcon').attr('src', 'path/to/new/image.png'); //change the img's source
});
EDIT (response to questions):
If you want this code to apply to all of your buttons, give each of your buttons a similar class instead of an ID:
<div class="colorButton"></div>
Then you can use the following selector to apply the above click listener to all of these divs:
$('.colorButton')
Naturally, you want to change your image as simply as possible. You could map all of your colors to their corresponding image file, but as far as design goes this might get messy and unwieldy. I would create a directory that stores all of your image files (for example, /your/color/swatches) and give each of them a name consistent with their color, like 'ff0000.png' for red, '0000ff.png' for blue, etc.
Why would we do this? So that we can switch your image based on the background-color attribute of your buttons. Let's say that you have the following buttons:
<div class="colorButton" style="background-color: '#ff0000'"></div>
<div class="colorButton" style="background-color: '#0000ff'"></div>
You can use the same click listener, but it will have to be modified a bit since we are mapping the background color to an image:
$('.colorButton').click( function() {
var color = $(this).css('backgroundColor');
//(You'll need to modify your color string here)
$('#imageIcon').attr('src', 'your/color/swatches/' + color + '.png');
});
BUT this won't work yet. Since most browsers return "rgb(xx, yy, zz)" from .css('backgroundColor'), you need to convert that string into hex. This post on SO gives a more or less effective way to do so, but you'll need to modify it to fit your model where I have indicated.