change background using javascript - javascript

I have to change the background of a div using JavaScript. I have managed to do that,
using document.getElementById('test').style.background = "url('img/test.jpg')";
Now, how do i change other properties like repeat, scroll,etc?
The css i want for the test is like
background: #f00 url('img/test.jpg') no-repeat fixed 10px 10px;
I cannot use jQuery, since I do not want to include the library for only a small thing.

Instead of setting all the css properties with javascript. I would suggest to create an additional css rule for this element with certain class. And then use javascript to add or remove this class from this element when you need it.
Eg.
function changeBG(){
var element = document.getElementById('test');
element.setAttribute("class", 'newBG'); //For Most Browsers
element.setAttribute("className", 'newBG'); //For IE; harmless to other browsers.
}

Below should work:
document.getElementById('test').style.background = "#f00 url('img/test.jpg') no-repeat fixed 10px 10px"
Or you can use individual properties such as backgroundColor of style object. See here for various properties of style object.

Make a class with those properties, and then just assign/remove that class through javascript.

function displayResult()
{
document.body.style.background="#f3f3f3 url('img_tree.png') no-repeat right top";
}
See following:
http://www.w3schools.com/jsref/prop_style_background.asp

As everyone suggests I also prefer using a class, but if you insist you can use JS for this as you use CSS
document.getElementById('test').style.background = "url('img/test.jpg') no-repeat fixed";

Use next style properties for changing background:
document.getElementById('test').style.background
document.getElementById('test').style.backgroundAttachment
document.getElementById('test').style.backgroundClip
document.getElementById('test').style.backgroundColor
document.getElementById('test').style.backgroundImage
document.getElementById('test').style.backgroundOrigin
document.getElementById('test').style.backgroundPosition
document.getElementById('test').style.backgroundPositionX
document.getElementById('test').style.backgroundPositionY
document.getElementById('test').style.backgroundRepeat
document.getElementById('test').style.backgroundSize
http://msdn.microsoft.com/en-us/library/ms535240%28v=vs.85%29.aspx

This will give the class to the dom element
document.getElementById('test').className = 'cssName'

Related

:hover doesn't work with jquery script

I have a <ul> where each li reponds on :hover. Here is the css:
.profile_nav_item:hover {
border-color: #af0621;
}
But it want these borders to stay colored when I click them.
I have this jQuery function:
$('a[rel="tab"]').click(function(e){
var url = $(this).attr('href');
$('.profile_nav_item').css('border-color', 'transparent');
$('.profile_nav_item', this).css('border-color', '#af0621');
But after clicking, the :hover css property isn't called anymore. Does anyone know how I could fix this?
Here is the fiddle: http://jsfiddle.net/zRJK9/
You need to reset CSS properties to '' (empty string) for the style sheet to kick in again.
$('.profile_nav_item').css('border-color', '');
basically you are forcing the element style to #af0621 after which the stylesheet will do nothing to override it (element styles take priority).
Passing an empty string value to css() removes the inline style setting.
JSFiddle: http://jsfiddle.net/zRJK9/6/
Because inline css attribute has more priority then included one. So when you set it with jQuery it got like this: style="border-color: #af0621". Try to use !important in your css:
.profile_nav_item:hover {
border-color: #af0621 !important;
}

Overwrite auto generated css

I am using a Jquery wysiwyg editor which at runtime automatically adds code to the textarea.
My problem is that it's inserting an inline style of style="width:320px" and I need to take that off as I've already set the styles to make it go 100%
Is there anyway to remove or overwrite that code with jquery
It's basically adding an inline style to a div with a class called wysiwyg...
so:
<div class="wysiwyg" style="width:320px">
The editor I'm having the trouble with is called: jWYSIWYG
Here's a demo url: http://akzhan.github.com/jwysiwyg/help/examples/
If you want to override inline styles you have two options:
Pure CSS:
.wysiwyg {
width: 120px !important;
}
jQuery:
$(".wysiwyg").css({width:120});
If you want to use styles from somewhere else you can also do:
$(".wysiwyg").css({width:"inherit"});
Reset the width using jQuery:
$('.wysiwyg').css('width', '100%');
Alternatively, you could remove the style attribute altogether:
$('.wysiwyg').removeAttr('style');
Have you tried declaring your own CSS with:
!important
eg.
#textarea-id { width: 300px !important; }
You can either define a new css rule with !important, or use jquery:
$("rule target").width(value);
This should work for you:
$('.wysiwyg').removeAttr("style");
or alternatively you can set the width to 100%
$('.wysiwyg').css("width", "100%");
You can remove undesired attributes on server-side with removeAttribute() DOM-method if you have server-side DOM manipulation module.
Or you can try to create your own slightly modified version of your WYSIWYG JS module.

Build JavaScript Object to use with jQuery .css() (what about duplicate keys?)

I use jQuery's .css() method to apply styles to an element. I do this like so:
var cssObj = {
'background-color' : '#000',
'background-image': '-webkit-linear-gradient(top,#000,#fff)',
'background-image': 'linear-gradient(top,#000,#fff)'
};
$(".element").css(cssObj);
The problem with this is that obviously I use duplicate keys in the object, which is not cool.
How can I solve this problem? I need to pass the CSS params with duplicate names to address most browsers.
Having multiple keys with the same name is not valid, and will generate an error in strict mode.
Create a function/plugin which applies the properties of your cssObj. If a string-string pair is found, set a CSS property with the desired value.
If an array is found, loop through it, and update the property with each value. If an invalid value is found, it's ignored.
DEMO: http://jsfiddle.net/RgfQw/
// Created a plugin for project portability
(function($){
$.fn.cssMap = function(map){
var $element = this;
$.each(map, function(property, value){
if (value instanceof Array) {
for(var i=0, len=value.length; i<len; i++) {
$element.css(property, value[i]);
}
} else {
$element.css(property, value);
}
});
}
})(jQuery);
// Usage:
var cssObj = {
'background-color': '#000',
'background-image': ['-webkit-linear-gradient(top,#000,#fff)',
'linear-gradient(top,#000,#fff)']
};
$(".element").cssMap(cssObj);
My advice would be to put your CSS into your stylesheet in it's own class, and simply add that class to your element instead. The browser itself will determine which of the background-image properties it supports, and will therefore only render that one.
CSS
.gradient-bg {
background-color: #000;
background-image: -webkit-linear-gradient(top, #000, #fff);
background-image: linear-gradient(top, #000, #fff)
}
jQuery
$(".element").addClass("gradient-bg");
You need to create a custom $.cssHooks (more info) that determines which one is the correct form,
by doing various tests --- or you could just use a css class with $.fn.addClass.
There is a repository of cssHooks on github for most properties. Writing your own hook is tricky, lots of edge cases.
https://github.com/brandonaaron/jquery-cssHooks
For background image gradient, you'd need:
https://github.com/brandonaaron/jquery-cssHooks/blob/master/gradients.js
It looks like you imply that .css() method works like CSS attributes in a .css file. I don't think it works like that. But here are few alternatives:
Use browser sniffing (why not? you already doing multi-browser CSS with vendor prefixes)
Use actual stylesheet linked as <link /> tag
Create <style> tag and add rules to it, dynamically.
Use style attribute: $('#my').attr('style', 'background: ...; bakground: ...; border-radius: ...; -moz-border-radius: ...;');

Changing CSS pseudo-element styles via JavaScript [duplicate]

This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
How to update placeholder color using Javascript?
(5 answers)
Closed 2 years ago.
Is it possible to change a CSS pseudo-element style via JavaScript?
For example, I want to dynamically set the color of the scrollbar like so:
document.querySelector("#editor::-webkit-scrollbar-thumb:vertical").style.background = localStorage.getItem("Color");
and I also want to be able to tell the scrollbar to hide like so:
document.querySelector("#editor::-webkit-scrollbar").style.visibility = "hidden";
Both of these scripts, however, return:
Uncaught TypeError: Cannot read property 'style' of null
Is there some other way of going about this?
Cross-browser interoperability is not important, I just need it to work in webkit browsers.
If you're comfortable with some graceful degradation in older browsers you can use CSS Vars. Definitely the easiest of the methods I've seen here and elsewhere.
So in your CSS you can write:
#editor {
--scrollbar-background: #ccc;
}
#editor::-webkit-scrollbar-thumb:vertical {
/* Fallback */
background-color: #ccc;
/* Dynamic value */
background-color: var(--scrollbar-background);
}
Then in your JS you can manipulate that value on the #editor element:
document.getElementById("#editor").style.setProperty('--scrollbar-background', localStorage.getItem("Color"));
Lots of other examples of manipulating CSS vars with JS here: https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/
To edit an existing one which you don't have a direct reference to requires iterating all style sheets on the page and then iterating all rules in each and then string matching the selector.
Here's a reference to a method I posted for adding new CSS for pseudo-elements, the easy version where you're setting from js
Javascript set CSS :after styles
var addRule = (function (style) {
var sheet = document.head.appendChild(style).sheet;
return function (selector, css) {
var propText = typeof css === "string" ? css : Object.keys(css).map(function (p) {
return p + ":" + (p === "content" ? "'" + css[p] + "'" : css[p]);
}).join(";");
sheet.insertRule(selector + "{" + propText + "}", sheet.cssRules.length);
};
})(document.createElement("style"));
addRule("p:before", {
display: "block",
width: "100px",
height: "100px",
background: "red",
"border-radius": "50%",
content: "''"
});
sheet.insertRule returns the index of the new rule which you can use to get a reference to it for it which can be used later to edit it.
EDIT: There is technically a way of directly changing CSS pseudo-element styles via JavaScript, as this answer describes, but the method provided here is preferable.
The closest to changing the style of a pseudo-element in JavaScript is adding and removing classes, then using the pseudo-element with those classes. An example to hide the scrollbar:
CSS
.hidden-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
JavaScript
document.getElementById("editor").classList.add('hidden-scrollbar');
To later remove the same class, you could use:
document.getElementById("editor").classList.remove('hidden-scrollbar');
I changed the background of the ::selection pseudo-element by using CSS custom properties doing the following:
/*CSS Part*/
:root {
--selection-background: #000000;
}
#editor::selection {
background: var(--selection-background);
}
//JavaScript Part
document.documentElement.style.setProperty("--selection-background", "#A4CDFF");
You can't apply styles to psuedo-elements in JavaScript.
You can, however, append a <style> tag to the head of your document (or have a placeholding <style id='mystyles'> and change its content), which adjusts the styles. (This would work better than loading in another stylesheet, because embedded <style> tags have higher precedence than <link>'d ones, making sure you don't get cascading problems.
Alternatively, you could use different class names and have them defined with different psuedo-element styles in the original stylesheet.
I posted a question similar to, but not completely like, this question.
I found a way to retrieve and change styles for pseudo elements and asked what people thought of the method.
My question is at Retrieving or changing css rules for pseudo elements
Basically, you can get a style via a statement such as:
document.styleSheets[0].cssRules[0].style.backgroundColor
And change one with:
document.styleSheets[0].cssRules[0].style.backgroundColor = newColor;
You, of course, have to change the stylesheet and cssRules index. Read my question and the comments it drew.
I've found this works for pseudo elements as well as "regular" element/styles.
An old question, but one I came across when try to dynamically change the colour of the content of an element's :before selector.
The simplest solution I can think of is to use CSS variables, a solution not applicable when the question was asked:
"#editor::-webkit-scrollbar-thumb:vertical {
background: --editorScrollbarClr
}
Change the value in JavaScript:
document.body.style.setProperty(
'--editorScrollbarClr',
localStorage.getItem("Color")
);
The same can be done for other properties.
Looks like querySelector won't work with pseudo-classes/pseudo-elements, at least not those. The only thing I can think of is to dynamically add a stylesheet (or change an existing one) to do what you need.
Lots of good examples here:
How do I load css rules dynamically in Webkit (Safari/Chrome)?

Can I apply shorthand css to elements using jQuery's .css() method?

I'm trying to apply unknown styles to unknown selectors and it would seem that shorthand css cannot be applied using jQuery's .css() method. Is this correct? Is there a work-around?
Note that I am building the object dynamically to be passed in to the .css() and do not want to use .css('background','#000') syntax.
$('#example').css({background:'#000000 url("images/bg.gif") repeat-x scroll 0 0 transparent'});
The code above doesn't work. However, the code below does.
$('#example').css({background:'#000'});
And so does this.
$('#example').css({background:'url("images/bg.gif")'});
But when used together they naturally overwrite each other. Any suggestions?
background: #000000 url("images/bg.gif") repeat-x scroll 0 0 transparent;
… is invalid CSS. You've specified the background-color twice (#000000 and transparent). It should work if you use valid CSS.
That said, using classes and external stylesheets is usually a better bet.
Your better option would be to have a set of pre-defined CSS classes in your CSS file and then apply those target styles on the fly as necessary.
This has the added benefit of keeping your jQuery code down to a readable and manageable level.
So instead of writing:
$('#example').css({background:'url("images/bg.gif")'});
You can opt for the simpler:
$('#example').addClass('myClass1');

Categories

Resources