I've searched SO and googled for this and there are many answers on how to read CSS propeties but non that allow the reading of a pseudo class property.
I have used the following to allow me to easily reuse certain pages (firmware/config upload) on a number of products.
.productname:before
{
content: "My Shiny New Product";
}
then
<span class="productname" />
in the html to insert the correct name.
Currently when sending a Firmware update to the Server no check is done on the client browser and the server returns [please reboot to contunue...] or [this is not a [productname] update file]. As you can imagine the firmware updates can be quite large and if transfered over 3G take some time.
I want to get the productname from the CSS :before pseudo class to allow me to check the upload file name before send it. I have implemented this JS Fiddle to illustrate the issue.
I have tried putting the content property on the .productname class directly (as a copy placeholder) and FF, Opera and Safari will read this but you guessed it IE returns undefined.
I know I can use a global var in JS and might have to do that but I'd rather have it defined in one place to avoid potential mistakes.
So does anyone know how to (or workaround ) read properies of the :pseudo CSS classes?
Thanks in advance.
Update
Since i cant get a solution for IE8, I've changed to using the following code instead.
window.addEvent( "domready",
function()
{
window.productName = "My Shiny New Product";
var def = '.productname:before { content: "'+window.productName+'"; }';
var style = new Element("style");
style.setAttribute( "type", "text/css" );
if( style.styleSheet )
{
style.styleSheet.cssText = def;
}
else
{
style.innerHTML = def;
}
document.getElementsByTagName("head")[0].appendChild(style);
document.getElementsByTagName("head")[0].appendChild(style);
} );
with reference to this site Dynamic SCRIPT and STYLE elements in IE
you can use window.getComputedStyle. however, an answer notes that some browsers may not support this, so tread lightly. here's a demo
<span class="test" />
<span class="test" />
<span class="test" />
.test:before{
content: "My Shiny New Product";
}
$(function() {
//get all element class test
var test = $('.test');
//each of them, alert the content
test.each(function() {
var style = window.getComputedStyle(this, "before");
alert(style.content);
});
});
Related
I am loading the below function in a empty HTML document ::
setTimeout(function() {
(function test(){
var elem = document.createElement('div');
body = document.body;
body.appendChild(elem);
var
rule = "lalalalallalaallllllllllllllaaaaaaaaaaaaaaa" ,
mod = 'Alex-z',
style = ['','<style id="s', mod, '">', rule, '</style>'].join('');
console.log(style);
elem.innerHTML += style;
})();
}, 2500);
Now I have a question, no matter how big rule is, I never see any text in the browser, why ? Can somebody explain, a very similar snippet is used in a JS feature detection library, called modenizer, so I would really be interested in knowing why nothing is showing up in my browser?
Because <style></style> is by default hidden in the browser and it is set display:none if you inspect element. It's because you wouldn't want your declared styles being showed in the browsers right?
I really don't know what you're going to do, but if you want to see your styles generated on that JS then use :
div style {
display: block;
}
You don't see any text in the browser because your output is:
"
<style id="sAlex-z">lalalalallalaallllllllllllllaaaaaaaaaaaaaaa</style>"
is the soft hyphen symbol and will be converted into the HTML name, which is and the result is not visible (http://www.ascii.cl/htmlcodes.htm)
The rest is just a <style> element, used only to set CSS rules and by default browser set style { display: none; }, so it's not visible.
a very similar sinppet is used in a JS feature detection library
called Modernizr
Yes, Modernizr use this kind of snippets to detect some features, because in most cases needs to create an empty element and try to set the property we are trying to test. Eg:
tests['textshadow'] = function() {
return document.createElement('div').style.textShadow === '';
}
The title attribute on a particular HTML element is not displayed in my application if viewed in Firefox. There are multiple topics explaining this problem. I was unable to find a sollution that would fit my needs. So I ask if you can please help.
I have a number of divs lined up. On mouseover each of the div's should display a different value(title). The title attribute works fine in Chrome but I need something simillar for Firefox.
The title attribute is set dynamically from Javascript!
My Javascript:
dojo.connect(div, 'mousemove',rasterTimeDisplay);
function rasterTimeDisplay() {
dojo.attr(evt.target, 'title', "some new title");
}
Why not to store the data to be displayed in another attribute ? Because you use javascript to feed your data-storage attribute, you can whatever you want.
For example, with jQuery :
//I feed my data-storage attribute
$("#my_div").attr('my-data', '<h1>my content to be displayed</h1>');
//And then i bind the hover event to toggle displaying of this data
$("#my_div").hover(
function(){
$(this).html($(this).attr('my-data'));
},
function(){
$(this).html('');
}
);
Or with standard JavaScript :
document.getElementById('my_div').my_data = '<h1>my content to be displayed</h1>';
document.getElementById('my_div').onmouseover = function(){
this.innerHTML = this.my_data;
};
document.getElementById('my_div').onmouseoout = function(){
this.innerHTML = '';
};
Sorry if i missunderstood you. However, you are trying to trigger the title attribute on hover? But the title attribute is already triggered by hover on default:
So if you just add the attribute to your desired element, you will get the extra information on hover.
var titles = document.getElementsByClassName('title');
for(var i = 0; i < titles.length; i++)
{
titles[i].title = 'Hover information ' + i;
}
jsFiddle
I you're interesting in the jQuery way to do this:
$('.title').attr('title', 'Hover information');
Still doesn't work?
Step-1: First try to run your firefox client in safe-mode. Your problem might be solved now. If this is the case proceed to step-2. Else... Well i would suggest you to update your grapical driver or install a newer version.
Step-2: Disable your Hardware Acceleration(AH).
Check another answer about this here: https://support.mozilla.org/nl/questions/860902
Now if you just want a work around, to even let the oldest Firefox browsers support this. You can find one here: Tooltips (title="...") won't show in Firefox
I hope this solved your problem.
attempting to have my webpage be a bit more dynamic by having the background change on some elements when a checkbox is clicked. I am trying to do this via class change and a CSS sheet. I have the following which is kicking out an error that my onclick function ins not defined (in IE9). More importantly will the webpage update if I only change the class of the object which would have a different class in the CSS file. Whats a better alternative if this does not work?
my elemenet and function
UPDATE
I made updates to both my HTML and CSS file as suggested by many. I am still getting no change in my webpage but the console is claiming that my function called from the onclick event is not defined which is a bit odd since it is. Also does this type for scripting belong in the HTML or should I pull it out and put in a seperate file. I figured since it was creating elements it belongs in the main html. Is there a cleaner more compact way of accomplishing this and not making my home screen html huge?
<tr class= 'tr.notchosen'><td><input type='checkbox' onclick='handleClick(this.id)'/></td></tr>
function handleClick(cb) {
var currentColumn = cb.parentNode
var currentRow = currentColumn.parentNode
if (currentRow.className === "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}
}
and my css file is the following
tr.chosen
{
background-color:rgba(255,223,0,0.75);
}
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
There are a couple of things going on here. First, your css selector is not quite right. In fact, I would suggest making the class name just "chosen" or "not chosen" and then selecting tr elements with that class.
<tr class='notchosen'>
And then you can target it from css (which was probably the original intention)
tr.notchosen
{
background-color:rgba(255,223,0,0);
}
Further, although I would not suggest using inline javascript, using your example, you should pass this if you want to work with the element and not this.id which would pass a string.
onclick='handleClick(this)'
The last part would be to sync up your javascript with the class name change
if (currentRow.className == "chosen")
{
currentRow.className = "notchosen";
}
else
{
currentRow.className = "chosen";
}
I'm not sure why, but I can't seem to get this to work.
Here is my function to enlarge my font.
<script type="text/javascript">
function growText() {
var text = document.getElementById("t_left_text");
text.font-size=22px;
</script>
And here is where I call it
<div id="t_left" onclick="growText()">
<br />
<p id="t_left_text">Mountains are beautiful land structures <br /> that are a result of plate tectonics.</p>
<br />
</div>
Try:
text.style.fontSize = "22px";
DEMO: http://jsfiddle.net/C2MWN/
When you want to change an element's CSS, you need to use the style property. To determine the name of the specific style property, the CSS name is converted to camel case - "font-size" becomes "fontSize", so that the identifier is valid in JavaScript.
While setting the style properties definitely works, and although this is a very simple example, it might be easier to deal with adding and removing a class. This is especially useful when setting multiple CSS properties. The class could be defined as:
.enlarged-font {
font-size: 22px;
}
And you would manipulate the text.className property (and/or the classList property).
Depending on the browser you're using, you could have easily provided a better description (as obvious as it was for some of us) of the problem by using the JavaScript console in the browser. In Firefox, you could use Firebug. In Internet Explorer and Chrome, you could use Developer Tools. If installed/enabled, these can usually be brought up by pressing the F12 on your keyboard.
Also, don't forget to close your function with a }.
Reference:
style property: https://developer.mozilla.org/en-US/docs/DOM/element.style
classList property: https://developer.mozilla.org/en-US/docs/DOM/element.classList
Use below code
function growText() {
var text = document.getElementById("t_left_text");
text.style.fontSize ="22px";
}
Working example http://jsfiddle.net/D2anZ/
Here's a version that uses CSS to accomplish what you want. That way if you want to do this to different sets of text at the same time, and want to change that font size, there's only one place you need to make the change. (Or if you also want to add other css properties (color, etc.)
Fiddle
JavaScript
function growText() {
var text = document.getElementById("t_left_text");
text.className = 'large-font';
}
CSS
.large-font {
font-size: 22px;
}
I've found plenty of information on how to change the background image of a div using JavaScript, but I am trying to use JavaScript to determine which background image is being displayed. The code to set the image goes like this:
document.getElementById("widgetField").style.background="url(includes/images/datepicker_open.png)";
I have tried every combination I can think of to access the background image url, but so far no dice:
alert(document.getElementById("widgetField").style.backgroundImage.url); - returns Undefined
alert(document.getElementById("widgetField").style.backgroundImage); - empty response
alert(document.getElementById("widgetField").style.background);
alert(document.getElementById("widgetField").style.background.image);
alert(document.getElementById("widgetField").style.background.url);
alert(document.getElementById("widgetField").style.background.image.url);
alert(document.getElementById("widgetField").style.background.value);
alert(document.getElementById("widgetField").style.background.image.value);
alert(document.getElementById("widgetField").style.background.image.value);
alert(document.getElementById("widgetField").style.backgroundImage.value);
Does anyone know how to do this? Is it possible?
BTW, here is the way the image is being set in CSS in the beginning:
#widgetField {
width: 290px;
height: 26px;
background: url(../images/datepicker_closed.png);
overflow: hidden;
position: relative;
}
UPDATE:
If I run the following, it works:
document.getElementById("widgetField").style.background="url(includes/images/datepicker_open.png)";
alert(document.getElementById("widgetField").style.background);
However, I cannot seem to access the URL property until it has been set by JavaScript, even though it is already defined in the CSS file. Is there a reason why the raw CSS setting is not accessible?
Try this:
var img = document.getElementById('widgetField'),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1);
You're setting the background property, background and backgroundImage are two seperate properties which is why backgroundImage is empty after setting background. If you want to access just the url part of the background property, you can use the following code:
var wfBg = document.getElementById("widgetField").style.background;
var wfBgUrl = wfBg.match(/(url\(['"]?([^)])['"]?\))/i);
if (wfBgUrl)
{
// Add your code here. wfBgUrl[1] is full string including "url()",
// wfBgUrl[2] would be just the url inside the parenthesis
}
For styles set by css documents:
if (window.getComputedStyle) // For standards compliant browsers
var wfBg = window.getComputedStyle(
document.getElementById("widgetField")
).getPropertyValue("background");
else // for IE
var wfBg = document.getElementById("widgetField").currentStyle.background;
The CSS backgorund prop may also include additional attributes as seen on https://developer.mozilla.org/en-US/docs/Web/CSS/background
background: no-repeat url("../../media/examples/lizard.png")
Using a simple img.style.background.slice(4, -1) will give wring results in these cases.
Why not use
/url\(".+"\)/i.exec(img.style.background)[0].replace(/^url\("/i, '').replace(/"\)$/i, '')
where /url\(".+"\)/i is a regex that matches the url("...") part, of which you take the first match with [0] and then replace the initial url(" with replace(/^url\("/i, '') and the ending ") with replace(/"\)$/i, '')
this should do it
alert( document.getElementById("widgetField").style['background-image'] );
You can do the following to get all the style properties after you have made changes ... so you see where the new things went ...
var style = document.getElementById("widgetField").style;
var allprops = '';
for ( i in style )
allprops += style[i] + ':' + i + '\n' ;
alert( allprops );
[EDIT] as i go along i will add here ..
Google Chrome: style['background-image']
Firefox 3.5.7: style.background
IE 6: style.background
style.backgroundImage work on all browsers ( IE6, IE7, FF 3.5.7, Google Chrome, Opera 10.10, Safari 4.0.4) for Windows ..
Get the background property:
alert(document.getElementById("widgetField").style.background);
Displays : url(includes/images/datepicker_open.png)
Edit: Andy E's answer should be close to what you need. One difference is that for IE you need
currentStyle.backgroundImage
instead of
currentStyle.background
Don't use these methods. Keep track of the background images in an array if you can. Different browsers will return different results when trying to get the background image value.
Firefox will return: 'url("../images/someimagefile.jpeg")'
Chrome will will return: 'url("https://www.yourdomain/images/someimagefile.jpeg")'
Just creating more problems if you ask me - and uncertainty with browser responses - including tablets.
I used the above methods of trying to read the background image file name first, and they caused more problems than I wanted - including on mobile devices.
I switched to keeping track of which images are in which div, by
using an array with the background image file names stored in the
array