I run the following code in the Firebug console.
$('img').css('border', 'solid 2px red').css('border');
The red image borders appear, but it returns an empty string, why is this?
It works fine in Chrome and Safari developer tools.
Update: The jQuery docs say that shorthand properties are not supported when getting CSS values. However I have also tried the following with no luck in Firefox (All work in Chrome and Safari)
$('img').css('border-style', 'solid').css('border-style');
$('img').css('borderStyle', 'solid').css('borderStyle');
$('img').css('border', 'solid 2px green').css('borderStyle');
Quoting .css docs.
Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.
For the case of border, you need to use the border-width, border-style and border-color related properties.
e.g. border-color:
$('img').css('border-top-color', 'red').css('borderTopColor');
$('img').css('border-right-color', 'red').css('borderRightColor');
$('img').css('border-bottom-color', 'red').css('borderBottomColor');
$('img').css('border-left-color', 'red').css('borderLeftColor');
Try this:
var border = $('img').css('border', '2px solid red')[0].style.border;
FIDDLE
Supported properties in firefox:
'border-top-color'
'border-right-color'
'border-bottom-color'
'border-left-color'
'border-top-width'
'border-right-width'
'border-bottom-width'
'border-left-width'
'border-top-style'
'border-right-style'
'border-bottom-style'
'border-left-style'
Are the supported longhands :) Cheers! Enjoy!!!
You can still use shorthand to set border in most cases.
If you are sure they are the same do something like
var borderString = $('img').css('border-top-width') + " "
+ $('img').css('border-top-style') + " "
+ $('img').css('border-top-color');
to get the string like "2px solid rgb(255,255,255)'
Perhaps you are trying to use multiple properties
use the following syntax
$('img').css({'border':'solid 2px red','color':'green'})
the shorthand property not supported in Jquery.
var objImage = $('img').css('border', 'solid 2px red');
objImage.css('border-top-color');
objImage.css('border-top-width');
objImage.css('border-top-style');
Not just for top, it is also applicable for right, left, and bottom.
This is also a non-working code :
objImage.css('border-style');
Since border, margin, padding properties of CSS is seperately editable. If border-top is different than border-left, browser may be confused which it must return when you just asked border.
Related
Scenario : Using pure Javascript only (no libraries), I need to increment (or decrement) the background colour opacity of an HTML element without affecting the opacity of any child element. The new opacity can be anywhere in the range of fully opaque to fully transparent. Support for browsers prior to IE9 is not required hence the chosen method to accomplish this is by using background-color property from getComputedStyle. I have only seen this return a string in two formats (using pure white as an example) :
rgba(255, 255, 255, 0.5) when opacity is applied.
rgb(255, 255, 255) when fully opaque - it changes to this format when opacity is 1.
I need to reset the background colour in the format, rgba(255, 255, 255, 0.5)
Code fragment :
myBG = window.getComputedStyle( myElement, null ).getPropertyValue( "background-color" );
myElement.style.backgroundColor = myBG.replace( /(.*)\((\s*\d+)\,(\s*\d+)\,(\s*\d+)(?:\,|\))(.*)/ , 'rgba( $2, $3, $4, ' + myNewOpacity.toString() + ' )' );
This works in the limited testing I have conducted - However :
Question 1. I am a beginner to Javascript and web development. Will I get any return formats that do not match the two above (cross browser compatibility issue) ?
Question 2. I am a complete novice to regular expressions. My solution seems heavy and/or inelegant. Is there a better regular expression I can use ? Is there a better alternative to using replace/regex ?
As far as I know, there are no other possible return values. If opacity is set, there can only be an rgba(...) return value, so in the mindset of defensive programming, you should only parse and modify the value if it is rgba (See also In Javascript how can I set rgba without specifying the rgb?)
See the above link for an easier to read solution without regex.
I want to change the chat window fontcolor/fontsize of the page younow. I tried 2 'cssText' samples but I'm unable to change the font color to RED. How can I change the chat window font color to RED? I'm using Firefox and greasemonkey.
sample 1:
document.getElementById("chatcomments").style.cssText = 'font-size: 36px; color: red !important;'
sample 2:
document.querySelector(".chatcomments span").style.cssText = 'font-size: 36px; color: red !important;'
click to see the chatimage
you need to be specific with the attributes of the style object:
document.getElementById("chatcomments").style.color = "red";
document.getElementById("chatcomments").style.fontSize = "30px";
If you use JQuery, you can use the css function, like so:
$(".chatcomments > span").css("color", "red");
You do not need to set font-size again if it already has been set. Another issue is that .chatcomments span won't work as they're two different things; instead, > will work: .chatcomments > span.
It is also better to use RGB or hexadecimal values instead of colour names, for example:
$(".chatcomments > span").css("color", "#EE4B38"); //RGB
$(".chatcomments > span").css("color", "rgb(238, 75, 56)"); //Hex
In the case that you're trying to create a custom client-side script in Tampermonkey or Greasemonkey (it looks like you are), you must use // #require to import the JQuery source (as seen in this answer):
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js
el.style.setProperty('color', 'red'); seems more right
Please consider the code snippet below:
<!DOCTYPE html>
<html>
<body>
<div id="mydiv">Sample Text</div>
<script type="text/javascript">
var md=document.getElementById("mydiv");
md.style.cssText="background-color:yellow !important;color:red;font-size:70px;font-weight:bold;";
setTimeout(function(){
md.style.backgroundColor="blue";
md.innerHTML+="<br/>Updated!";
},2000);
</script>
</body>
</html>
Explanation: I am trying out the cssText browser support and noticed that cssText is not working as per my expectation in Firefox, Opera browsers.
The above code defines "background-color:yellow !important" and after 2 seconds the background-color is changed to blue. But since I have specified '!important' in my cssText, I assume the background-color should not get updated. This works in IE, Chrome, Safari. But not in Firefox, Opera.
Can someone please suggest.
EDIT: I want to specify the !important rule for a css property and restrict further changes to it via javascript. I would like to achieve this using JavaScript i.e. specifying !important via JavaScript. Any help on this would be appreciated.
Stumbled across this question while googling for something else.
The first thing to understand, is that cssText doesn't create another style: It is merely a shorthand that lets you assign multiple styles at once. The following are roughly identical:
element.style.cssText = "background-color:yellow;color:red;";
element.style.backgroundColor = "yellow";
element.style.color = "red";
The only real thing to note, is that I believe that assigning to cssText will overwrite any existing element styles. Eg, the following will result in a style that is exactly equal to color:red; and not equal to background-color:yellow;color:red;. cssText effectively removes any existing element styles before applying the ones specified:
element.style.backgroundColor = "yellow";
element.style.cssText = "color:red;";
The second thing to realize, is that !important doesn't make a style read-only. It only prevents defined styles of higher specificities being used, and only does so as long as it is defined. When you assign the background color value of blue, you are effectively removing !important from the declaration. You'd have to set your background color as background-color:blue !important; in order to keep it.
In short, if something overwrites your background-color:yellow !important; with background-color:blue;, there's nothing you can do about it. Unless you do some other fancy work, like creating a timer interval that every X milliseconds resets the yellow !important style. But then you run into problems of having to keep track of the interval, especially if you may actually want to set the background color to some other value, otherwise it will just get overwritten on you!
var element = ...;
setInterval(1000, function(){
if (element.style.backgroundColor != "yellow !important") {
element.style.backgroundColor = "yellow !important";
}
});
The one thing I can think of, is if these styles are set in stone, you could just make them actual rules instead of inline element styles. You can keep the !important tag if you make it a rule:
.bg-yellow {
background-color: yellow !important;
}
element.className = "bg-yellow";
Here is your JS modified code. I've checked in FF 27 and it is working.
var md=document.getElementById("mydiv");
md.style.cssText="background-color:yellow !important;color:red;font-size:70px;font-weight:bold;";
setTimeout(function(){
md.style.setProperty="background-Color:blue"; //modified this line
md.innerHTML+="<br/>Updated!";
},2000);
Here is the Working Demo for you.
http://jsbin.com/kifozeka/2/edit
It seems that when I use jQuery's addClass function adding a class with a 2px border, that it returns the old value at times and not the new when outputting the css in an iframe. I assume that this happens only sometimes due to how fast the class gets added. For example:
Stylesheet:
.testBorder {
border: 2px solid #000;
}
JavaScript:
var iframe = $('#contentFrame').contents();
var obj = $('#someObj',iframe);
obj.addClass('testBorder');
console.log(obj.css('border-top-width'));
console.log(obj.css('border-left-width'));
The border values outputted are often 0 instead of 2px. I can do something like:
obj.delay(500).queue(function(){
console.log($(this).css('border-top-width'));
console.log($(this).css('border-left-width'));
$(this).dequeue();
});
But looking to apply it immediately after the class is added as I use the values to positon correctly to not look like its jumping.
The CSS is being applied and is reflected, so I know it is updating and not being overridden by another style.
The jQuery version I am using is 1.10.2 with the jQuery Migrate v1.2.1 and I am using the jQuery UI.
Try this:
var iframe_content = ($.browser.msie ? $('#contentFrame').get(0).contentWindow.document) : $('#contentFrame').get(0).contentDocument));
var obj = iframe_content.find('#someObj');
obj.queue(function() { /** check for border width here **/ });
obj.addClass('testBorder').dequeue(); /* this last .dequeue() may not be necessary */
I get this problem in IE7 when running a piece of code that uses jquery and 2 jquery plugins. The code works in FF3 and Chrome.
The full error is:
Line: 33
Char: 6
Error: bg is null or not an object
Code: 0
URL: http://localhost/index2.html
However line 33 is a blank line.
I am using 2 plugins: draggable and zoom. No matter what I do to the code it is always line 33 that is at fault. I check the source has update via view source but I feel this could be lying to me.
<body>
<div id="zoom" class="zoom"></div>
<div id="draggable" class="main_internal"><img src="tiles/mapSpain-smaller.jpg" alt=""></div>
<script type="text/javascript">
$(document).ready(function() {
$('#draggable').drag();
$('#zoom').zoom({target_div:"draggable", zoom_images:new Array('tiles/mapSpain-smaller.jpg', 'tiles/mapSpain.jpg') });
});
</script>
</body>
Essentially what I am trying to do is recreate the Pragmatic Ajax map demo with jQuery.
It would appear that the second line of this snippet is causing the trouble:
bg = $(this).css('background-position');
if(bg.indexOf('%')>1){
It seems to be trying to select the background-position property of #draggable and not finding it? Manually adding a background-position: 0 0; didn't fix it. Any ideas on how to get around this problem?
I tried using the MS Script Debugger but that is nearly useless. Can't inspect variables or anything else.
A bit more digging about on the Interweb has revealed the answer: IE doesn't understand the selector background-position. It understands the non-standard background-position-x and background-position-y.
Currently hacking something together to workaround it.
Nice one, Redmond.
To get around the fact that Internet Explorer does not support the "background-position" CSS attribute, as of jQuery 1.4.3+ you can use the .cssHooks object to normalize this attribute between browsers.
To save yourself some time, there is a background position jQuery plugin available that allows both "background-position" and "background-position-x/y" to work as expected in browsers that don't support one or the other by default.
It is interesting. IE8 doesn't understand getter backgroundPosition, but it understands setter.
$('.promo3').mousewheel(function(e,d){
var promo3 = $(this);
var p = promo3.css('backgroundPosition');
if (p === undefined) {
p = promo3.css('backgroundPositionX') + ' ' + promo3.css('backgroundPositionY');
}
var a = p.split(' ');
var y = parseInt(a[1]);
if (d > 0) {
if (y < -1107) y += 1107;
y -= 40;
}
else {
if (y > 1107) y -= 1107;
y += 40;
}
promo3.css('backgroundPosition', a[0] + ' ' + y + 'px');
return false;
});
It works great in IE8 and IE8 compatible view.
This worked for me:
if (navigator.appName=='Microsoft Internet Explorer')
{
bg = $(drag_div).css('backgroundPositionX') + " " + $(drag_div).css('backgroundPositionY');
}
else
{
bg = $(drag_div).css('background-position');
}
hope it does for you.
You may want to check to make sure that you are loading your js files in the correct order so that any dependencies are taken into account.
A bit of thinking (and a cup of tea) later I came up with:
if(bg == 'undefined' || bg == null){
bg = $(this).css('background-position-x') + " " + $(this).css('background-position-y');
}
Unfortunately it returns center center despite the online resources I can find state it should return 0 0 if the values are undefined.
Beginning to wonder if there is an actual fix/workaround to this. A lot of people have tried and all so far fail to catch all edge cases.
The camelCase version of backgroundPosition seems viable but I don't know enough of jQuery to make an accurate assessment of how to go about it - from what I have read you can only use camelCase as getters if the property has been set previously. Please tell me if I am mistaken.
However line 33 is a blank line.
It'll be line 33 of one of your .js files, not line 33 of the HTML itself. IE fails to report which actual file the error was in. Look at line 33 of each .js for something about ‘bg’; if the worst comes to the worst you can start inserting newlines at the start of each .js and see whether the line number changes.
I check the source has update via view source but I feel this could be lying to me.
View source will always show you what IE got from the server. It won't show any updates to the DOM.
try backgroundPosition istead
Also, make sure that 'this' exists and that your request for an attribute returns a value. IE will throw this kind of errors when you try to call a method on a property that does not exist, therefore bg is null or null an object. if you dont care about IE you can do bg = $(this)... || '' so that theres always something referenced.
Also, unrelated to the error you're getting, but is your index value of 1 correct? Did you mean -1 ?
Yupp, Try background-position instead or just set the background-position with jquery before you call it. Ill guess one often knows the positions through CSS before calling it. It isnt pretty, but somehow it did the trick for me.)
eg:
//set it in with javascript.
$("someid").css("background-position", "10px 0");
...
//do some funky stuff
//call it
$("someid").css("background-position");
//and it would return "10px 0" even in IE7
if nothing helps, it's also possible to make the following trick.
We can replace a background of an element by an inner absolutely positioned element (with the same background). The coordinates will be replaced by left and top properties. This will work in all browsers.
For better understanding, please, check the code:
Before
<div></div>
div {
background: url(mySprite.png);
background-position: -100px 0;
}
After
<div>
<span></span>
</div>
div {
position: relative;
overflow: hidden;
width: 100px; /* required width to show a part of your sprite */
height: 100px; /* required height ... */
}
div span {
position: absolute;
left: -100px; /* bg left position */
top: 0; /* bg top position */
display: block;
width: 500px; /* full sprite width */
height: 500px; /* full sprite height */
background: url(mySprite.png);
}
This solution is not very flexible, but it helped me to show icons hover state properly.
You can't use dashes in the jquery css function. You have to do it in camelCase:
.css('backgroundPosition') or .css('backgroundPositionX') and .css('backgroundPositionY') for IE