How to add background-image to a div? - css

I am working with the Mojo SDK and I'am trying to add a background image to a div but havn't been able to find a way to do it.
Obviously I have tried doing it the normal CSS-way but it doesn't seem to work with Mojo.
Here is the latest thing I tried:
var t=document.getElementById("kblayoutdiv");
t.parentNode.removeChild(t);
var t=document.getElementsByTagName("BODY")[0];
var div=document.createElement("div");
div.style.position="fixed";
div.id="kblayoutdiv";
div.style.display="block";
div.style.top="80%";
div.style.left="92%";
div.style.width="16px";
div.style.height = "11px";
div.style.background = url('/usr/palm/frameworks/mojo/keyb_en-us.png');
div.style.zIndex = "255";
t.appendChild(div);
window.kblayout="en";
I have tried several solutions to get the background image to show.
The rest is working fine. It is just the background iamge that won't show no matter what.
So if anyone can show me the piece of code to add the background image I'd be real happy :)

div.style.background = url('/usr/palm/frameworks/mojo/keyb_en-us.png');
You have to quote strings in JavaScript
div.style.background = "url('/usr/palm/frameworks/mojo/keyb_en-us.png')";
Obviously, the URI has to be correct as well.
That said, as a rule of thumb, it is almost always better to predefine all your styles in an external stylesheet and generate elements that match the selectors (e.g. by setting .className).

Related

How can I apply according style as attribute for SVG Elements in D3 or JS

When I use D3 to manipulate SVG elements, I applied both attr(such as x, y cx, cy) and style(such as stroke, text-anchor, fill) to SVG Element, for D3 itself only, this works pretty well,
but when I try to use html2Canvas.js to take a snapshot, then the style part in SVG elements become buggy, I gave a few tries, it turns out when I put those style as attr, then everything works again, so I wonder how can I move all valid styles into attr(I need to keep the style, cos I sometimes, only setting as style can work)
Or another direct help could be how could I make html2canvas recognize both attr and style and just get their final cooperative effect.
Try converting the svg to canvas first. There is a project https://github.com/gabelerner/canvg out there, which may help you. After converting the svg, html2canvas should be able to render the snapshot correctly.
If we are only talking about styles that are set via style attributes, not using a stylesheet, then the following is an option that is independant of d3:
var svgElements = document.querySelectorAll("svg *");
Array.prototype.forEach.call(svgElements, function(svgElement){
var styles = svgElement.getAttribute("style").split(";");
styles.forEach(function(style){
var styleComponents = style.split(":");
svgElement.setAttribute(
styleComponents[0].trim(),
styleComponents[1].trim()
);
});
});
You'll have to modify the selector in the first line to match your use case.

Why does the transform-origin CSS property not show up in React?

I am manipulating CSS styles using React with code that resembles this:
let el React.findDOMNode(this.refs.thing);
el.style.transform = `translate(${0}px, ${0}px) scale(${1})`;
el.style.transformOrigin = `${100}px ${100}px)`; // SPOT THE TYPO
The transform CSS property works and shows up when I inspect the element in the browser (Chrome). The transform-origin property does not show up, and I cannot figure out why.
I log to the console just before this code, so it is being executed. When I intentionally do something like:
el.style['transform-origin'] = etc.
I don't get a warning from React, despite using the development build.
As spotted by wintvelt, there was a spurious parenthesis in my code:
el.style.transformOrigin = `${100}px ${100}px`;
is correct.

How to change backgrond-color of any website page through url?

I am facing a problem related to css.My question is that I want to change background-color to black of any website page through url. I want this for study better to protect my eyes meanwhile I have eye problem. So what code to apply in the url to show the page black meanwhile we use this css rule like body {
background-color:#00000;} to output .I have attached two images for it to clear more better.Hope will get response as soon as possible.Thank you too much!
I think the best solution for you to it to take some of the recommendations above, and turn it into a bookmarket! That way, you can always click the button in your address bar and it will
1) Load jQuery if necessary
2) Change the background-color of <html> and <body> elements to black.
Here's a link to the JSFiddle. Drag the link to your bookmarks bar and watch the magic happen:
http://jsfiddle.net/lasha/GjQGZ/
No need for all the extra steps! :)
I would suggest you use some kind of glare reduction/warmer color software, like F.lux.
I use it and even with white backgrounds, my eyes don't get tired as much.
For SO site, where Jquery is used, you can type this in the console:
$('body').css('background-color', '#000');
And also you can change the text color to white:
$('body').css('color', '#fff');
If no Jquery is loaded, you can selet the body tag with document.getElementByTagName
you can't do it through a URL. However, since you're using firefox:
Alternatively, look in to a plugin like greasemonkey (or similar) and inject custom CSS styles on to the page you're viewing. Something like:
// ==UserScript==
// #name Readability Helper
// #description makes font more readable for custom viewing.
// #namespace CSS
// #include *
// #version 1.0
// ==/UserScript==
(function(w){
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = "* {color:#fff !important;background-color:#fff !important";
w.document.body.appendChild(css);
})(unsafeWindow);
Brad already gave a good answer.
Alternatively you could use the Firefox add-on Color That Site!
The purpose of this Add-on is to let you easily change the colors of any web site you want. These color edits can be permanently saved and be im-/exported for sharing.
This can be done by applying some javascript to the site. After site is loaded, you can write in the address bar something like this:
javascript:document.body.style.backgroundColor = "#000";
Make sure to include 'javascript:' prefix part (if you copy/pasted it might happen that browser excluded it for security reasons).
This will work only locally, of-course!
UPDATE: If it happen for some reason this doesn't work in chrome, try to do it like this:
javascript:document.body.style.backgroundColor = "#000"; alert()
I didnt figure why or how but it works!
You cannot do such things with a URL (unless the server specified in the URL has special functionality for this).
You can use a user style sheet or browser add-on to impose your CSS rules. The ways to do such things depend on browser.
When using a user style sheet, you mostly need the !important specifier, since by default page (author) style sheet rules override use style sheet rules. Example:
body { background: black !important;
color: white !important; }
Note that this also overrides any background image that pages might set for body. And setting color whenever you set background is a good idea—you don’t want to see black on black, or even dark gray on black.
But it’s really more complicated. Any element can have a background (and content color) of its own. For example, if a page has <body><div id=content>...</div></body> and it sets background on that div, then you settings for body won’t have much effect.
At the extreme, you could replace body by * in the rule above, to make everything white on black, except those ingredients that are not under CSS control (like contents of images and possibly some form fields).

SVG used as background-image loses embed images?

I'm using svg's as background-images for a responsive layout that recreates a complex brochure in online format.
Everything works perfectly for vector objects however if I embed images on the svg they don't appear on the background.
The strangest thing is if I check the svg on its own, the images are there, so this is kind of annoying!
Does anyone know if it has something to do with the svg configuration or something like that?
How can I solve this and still be able to use the svg as a background-image (background-size:cover rules!)?
Oh I should add that I've seen this "phenom" happen on chrome in my mac, if it's browser specific please say so!
The svg in question is this: http://nonstoptrip.limsomnium.com/img/fundoinfo1.svg
Unfortunately I'm not much of a jsfiddler so I couldn't create something to show you all.
Thanks in advance!
The images will appear if you load the svg at the document level. You can remove this element later and the images won't disappear. You can set it to load into a 1px x 1px element...
function loadSVG(svgpath){
if( /webkit/gi.test(navigator.userAgent.toLowerCase()) ){
var obj = document.createElement("object");
obj.setAttribute("type", "image/svg+xml");
obj.setAttribute("data", svgpath);
obj.setAttribute("width", "1");
obj.setAttribute("height", "1");
obj.setAttribute("style", "width: 0px; height: 0px; position: absolute;visibility : hidden");
document.getElementsByTagName("html")[0].appendChild(obj);
}
}
window.onload = function(){
loadSVG("../img/mySVG.svg");
}
The author of this technique is Dirk Weber, here are more details: http://www.eleqtriq.com/2012/01/enhancing-css-sprites-and-background-image-with-svg/
Webkit simply doesn't support this yet I'm afraid. https://bugs.webkit.org/show_bug.cgi?id=63548 is tracking this issue.
#Duopixel, using just "image/xml" for the type attribute also works (I've only tested it in chrome) and doesn't cause a "Resource interpreted as Document but transferred with MIME type image/svg+xml" error (while "image/svg+xml" does). Hope this helps get rid of that annoying error in the console you may be getting!

Is it possible to create a new css property?

Is it possible to create a new property in CSS? For example, say you're developing a control that displays a photo and you want to add a property to css to control what style frame to have around the photo. Something like:
#myphoto { frame-style: fancy }
Is there some way to do this in a cross browser compatible manner, and how would you define whether the style inherits or not?
EDIT: It's a custom control - your JS code would deal with the style - I'm not expecting the browser to magically know what to do. I want the user to be able to style the control with CSS instead of JS.
Sure, why not. Check this out as an example: http://bililite.com/blog/2009/01/16/jquery-css-parser/
You may also be able to get away with using CSS classes instead of properties. Not sure if that works for what you're doing.
You can't. Browsers interpret CSS based on how their layout engines are coded to do so.
Unless you took an existing open source engine like WebKit or Gecko, added custom code to handle your custom CSS and made a browser that used your customized layout engine. But then only your implementation would understand your custom CSS.
Re your edit: it'd depend on whether you're able to read that style somehow. Typically browsers just instantly discard any properties they don't recognize, and CSS is not normally reachable by JavaScript because CSS code is not part of the DOM.
Or you could look at Jordan's answer.
If you'd prefer a straight JavaScript solution that uses no JS libraries, you could use the query string of a background-image to keep "custom properties" inside your CSS.
HTML
<div id="foo">hello</div>
CSS
#foo {
background: url('images/spacer.gif?bar=411');
}
JavaScript
getCustomCSSProperty('foo', 'bar');
Supporting JavaScript Functions
function getCustomCSSProperty(elId, propName)
{
var obj = document.getElementById(elId);
var bi = obj.currentStyle ? obj.currentStyle.backgroundImage : document.defaultView.getComputedStyle(obj, null).getPropertyValue('background-image');
var biurl = RegExp('url\\(["\\\']?([^"\\\']+)["\\\']?\\)').exec(bi);
return getParameterByName(propName, biurl[1]);
}
function getParameterByName(name, qs) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(qs);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
Demo:
http://jsfiddle.net/t2DYk/1/
Explanation:
http://refactorer.blogspot.com/2011/08/faking-custom-css-properties.html
I've tested the solution in IE 5.5-9, Chrome, Firefox, Opera, and Safari.

Resources