Add CSS to a JavaScript button - javascript

On my project I use JS Buttons a lot, I can't find a way to add CSS to them. Can you help?
leftBtn = document.createElement('button');
leftBtn.innerText = "<";
rightBtn = document.createElement('button');
rightBtn.innerText = ">";
fireBtn = document.createElement('button');
fireBtn.innerText = "*";
Using CSS classes to change buttons:
<button class="btn">default button</button>
Class used

You could use this code to add a css class to each button:
leftBtn.className = "leftOne";
rightBtn.className = "rightOne";
fireBtn.className = "fireOne";
Then you can use regular css to style them.

You could add a class to your buttons, and then add any styling in CSS:
leftBtn.className = "class_name"

You probably need to use the className to your Javascript:
EXAMPLE:
leftBtn.className = "name";
Hope this helps :)

you can use for example :
leftBtn.style.color = "blue";
Lear more about in https://developer.mozilla.org/es/docs/Web/API/HTMLElement/style

In general, there are two main ways to do that.
The first one using inline styles, just keep in mind that inline style has the highest precedence in a document.
elt.style.color = '...'
or
elt.setAttribute('style', '...')
More info here
The second is by using the class name. You can simply define a class name and write CSS for this class name.
element.className.add = 'your-class-name'
then
.your-class-name { color: red }
In a second way, you can manage class names by using methods like add, remove, toggle
More info here

Just do something like this
leftBtn.style.marginLeft = '20px'
rightBtn.style.marginLeft = '20px'
I guess it

var leftBtn = document.createElement('button');
leftBtn.innerText = "<";
leftBtn.className = "test_style"; // Set class name
leftBtn.style.color = "#000"; // You can also set style properties inline
...
Here is a playground:
https://jsfiddle.net/u5hojsgb/

Related

Add div onclick with javascript

I am completely new to Javascript (and Stack Overflow) and I want to build a blog that allows the user to create a div onclick. I referenced this article on w3shool and tried all the three methods listed. However, the div doesn't show up when I use the first two methods and appears without clicking when I use the third one.
Here's my code for the third method:
HTML
<button class="box4" id="newEntry">NEW</button>
Javascript
const parent = document.getElementById("entries");
document.getElementById("newEntry").addEventListener("click", newEntry);
function newEntry() {
var newDiv = document.createElement("div");
parent.appendChild(newDiv);
}
For the second method, I replaced line 2 with
document.getElementById("newEntry").onclick= function () {newEntry()};
I have seen similar questions, but none of them solved my problem, so I would really appreciate your help.
There's nothing wrong with you code.
It works fine.
just one thing you have to remember: Div by default have no height, so if you want make sure to visualize it, just add height and color to it, like the code bellow.
const parent = document.getElementById("entries");
parent.style.width = '150px';
parent.style.height = '150px';
parent.style.backgroundColor = 'red';
document.getElementById("newEntry").addEventListener("click", newEntry);
function newEntry() {
var newDiv = document.createElement("div");
newDiv.style.width = '50px';
newDiv.style.height = '50px';
newDiv.textContent = 'Entry';
newDiv.style.backgroundColor = 'white';
parent.appendChild(newDiv);
}
<div id="entries"></div>
<button id="newEntry">new Entry</button>
Here is an example:
You can use querySelectorAll with a css selector to query all the elements matching the selector, but you can use the getElementByName too. In your example you query the elements by ID, but I don't se where you set the ids.
function onInitClick(){
const buttons = document.querySelectorAll('button');
const secondButton = buttons[1];
secondButton.addEventListener('click', createButtonAndAppend);
secondButton.innerText = 'Click me';
}
function createButtonAndAppend(){
const button = document.createElement('button');
button.addEventListener('click', createButtonAndAppend);
button.innerText = 'Adds another button';
document.body.append(button);
}
<button onclick="onInitClick();">Add click to second button</button> <button>Nothing happens</button>
you can do it simply using jquery.
if you want to add something to div,
$("#your_div_id").html("your child element")
for example
<div id="example"></div>
$("#example").html("<h1>Hello world</h1>")
then result is
<div id="example"><h1>Hello world</h1></div>

append css inline styles in js button for hover [duplicate]

I've created the following...
var menu = document.createElement('select');
How would I now set CSS attributes e.g width: 100px?
Use element.style:
var element = document.createElement('select');
element.style.width = "100px";
Just set the style:
var menu = document.createElement("select");
menu.style.width = "100px";
Or if you like, you can use jQuery:
$(menu).css("width", "100px");
For most styles do this:
var obj = document.createElement('select');
obj.style.width= "100px";
For styles that have hyphens in the name do this instead:
var obj = document.createElement('select');
obj.style["-webkit-background-size"] = "100px"
That's actually quite simple with vanilla JavaScript:
menu.style.width = "100px";
Just for people who want to do the same thing in 2018
You can assign a CSS custom property to your element (through CSS or JS) and change it:
Assigment through CSS:
element {
--element-width: 300px;
width: var(--element-width, 100%);
}
Assignment through JS
ELEMENT.style.setProperty('--element-width', NEW_VALUE);
Get property value through JS
ELEMENT.style.getPropertyValue('--element-width');
Here useful links:
https://developer.mozilla.org/en-US/docs/Web/CSS/--*
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/removeProperty
All of the answers tell you correctly how to do what you asked but I would advise using JavaScript to set a class on the element and style it by using CSS. That way you are keeping the correct separation between behaviour and style.
Imagine if you got a designer in to re-style the site... they should be able to work purely in CSS without having to work with your JavaScript.
In prototype I would do:
$(newElement).addClassName('blah')
When debugging, I like to be able to add a bunch of css attributes in one line:
menu.style.cssText = 'width: 100px';
Getting used to this style you can add a bunch of css in one line like so:
menu.style.cssText = 'width: 100px; height: 100px; background: #afafaf';
if you want to add a global property, you can use:
var styleEl = document.createElement('style'), styleSheet;
document.head.appendChild(styleEl);
styleSheet = styleEl.sheet;
styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
<h1>Silence and Smile</h1>
<input type="button" value="Show Red" onclick="document.getElementById('h1').style.color='Red'"/>
<input type="button" value="Show Green" onclick="document.getElementById('h1').style.color='Green'"/>
This works well with most CSS properties if there are no hyphens in them.
var element = document.createElement('select');
element.style.width = "100px";
For properties with hyphens in them like max-width, you should convert the sausage-case to camelCase
var element = document.createElement('select');
element.style.maxWidth = "100px";
<body>
<h1 id="h1">Silence and Smile</h1><br />
<h3 id="h3">Silence and Smile</h3>
<script type="text/javascript">
document.getElementById("h1").style.color = "Red";
document.getElementById("h1").style.background = "Green";
document.getElementById("h3").style.fontSize = "larger" ;
document.getElementById("h3").style.fontFamily = "Arial";
</script>
</body>

Change CSS on element with JavaScript?

I'm new to frontend development, and I want to rezize an <img> with JavaScript:
Which element?
<div class="dz-image">
<img data-dz-thumbnail="" alt="principal.png" src="http://localhost:49407/file/Image/660">
</div>
What function im using in js?
this.emit("thumbnail", mockFile, "http://localhost:11111/file/Image/" + principal)
{ document.querySelector('data-dz-thumbnail') };
I'm using querySelector to get the spefic <img> element.
Is it possible to add some style directly on that line like height:120; width: 120;?
Yes,it is possible to add some style directly.
let ele = document.querySelector('[data-dz-thumbnail]')
ele.style.width="120px"
ele.style.height="120px"
Per my understanding, queryselector should be classname, id or tag
Second you can add css by taking a variable for your querySelector line. It is like:
var el = document.querySelector('div');
el.style.backgroundColor = 'green';
el.style.display = 'none';
el.style['border-radius'] = '5px';
I solved this using jQuery's .css() method like this:
$('[data-dz-thumbnail]').css('width', '120');
$('[data-dz-thumbnail]').css('height', '120');

Changing element style attribute dynamically using JavaScript

I hav a certain style sheet for a div. Now i want to modify one attribute of div dynamically using js.
How can i do it?
document.getElementById("xyz").style.padding-top = "10px";
Is this correct?
In addition to other answers, if you want to use the dash notition for style properties, you can also use:
document.getElementById("xyz").style["padding-top"] = "10px";
It's almost correct.
Since the - is a javascript operator, you can't really have that in property names. If you were setting, border or something single-worded like that instead, your code would work just fine.
However, the thing you need to remember for padding-top, and for any hyphenated attribute name, is that in javascript, you remove the hyphen, and make the next letter uppercase, so in your case that'd be paddingTop.
There are some other exceptions. JavaScript has some reserved words, so you can't set float like that, for instance. Instead, in some browsers you need to use cssFloat and in others styleFloat. It is for discrepancies like this that it is recommended that you use a framework such as jQuery, that handles browser incompatibilities for you...
There is also style.setProperty function:
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty
document.getElementById("xyz").style.setProperty('padding-top', '10px');
// version with !important priority
document.getElementById("xyz").style.setProperty('padding-top', '10px', 'important');
I resolve similar problem with:
document.getElementById("xyz").style.padding = "10px 0 0 0";
Hope that helps.
Assuming you have HTML like this:
<div id='thediv'></div>
If you want to modify the style attribute of this div, you'd use
document.getElementById('thediv').style.[ATTRIBUTE] = '[VALUE]'
Replace [ATTRIBUTE] with the style attribute you want. Remember to remove '-' and make the following letter uppercase.
Examples
document.getElementById('thediv').style.display = 'none'; //changes the display
document.getElementById('thediv').style.paddingLeft = 'none'; //removes padding
document.getElementById("xyz").style.padding-top = '10px';
will be
document.getElementById("xyz").style["paddingTop"] = '10px';
I would recommend using a function, which accepts the element id and an object containing the CSS properties, to handle this. This way you write multiple styles at once and use standard CSS property syntax.
//function to handle multiple styles
function setStyle(elId, propertyObject) {
var el = document.getElementById(elId);
for (var property in propertyObject) {
el.style[property] = propertyObject[property];
}
}
setStyle('xyz', {'padding-top': '10px'});
Better still you could store the styles in a variable, which will make for much easier property management e.g.
var xyzStyles = {'padding-top':'10px'}
setStyle('xyz', xyzStyles);
Hope that helps
Surprised that I did not see the below query selector way solution,
document.querySelector('#xyz').style.paddingTop = "10px"
CSSStyleDeclaration solutions, an example of the accepted answer
document.getElementById('xyz').style.paddingTop = "10px";
document.getElementById("xyz").setAttribute('style','padding-top:10px');
would also do the job.
document.getElementById('id').style = 'left: 55%; z-index: 999; overflow: hidden; width: 0px; height: 0px; opacity: 0; display: none;';
works for me
I change css style in Javascript function.
But Uncaught TypeError: bild is null .
If I run it in a normal html file it work.
CODE:
var text = document.getElementById("text");
var bild = document.getElementById("bild");
var container = document.getElementById("container");
bild.style["background-image"] = "url('stock-bild-portrait-of-confident-senior-business-woman-standing-in-office-with-her-arms-crossed-mature-female-1156978234.jpg')";
//bild.style.background-image = "url('stock-bild-portrait-of-confident-senior-business-woman-standing-in-office-with-her-arms-crossed-mature-female-1156978234.jpg')";
// bild.style["background-image"] = "url('" + defaultpic + "')";
alert (bild.style["background-image"]) ;
bild.style["background-size"] = "300px";
bild.style["background-repeat"] = "no-repeat";
bild.style["background-position"] = "center";
bild.style["border-radius"] = "50%";
bild.style["background-clip"] = "border-box";
bild.style["transition"] = "background-size 0.2s";
bild.style["transition-timing-function"] = "cubic-bezier(.07,1.41,.82,1.41)";
bild.style["display"] = "block";
bild.style["width"] = "100px";
bild.style["height"] = "100px";
bild.style["text-decoration"] = "none";
bild.style["cursor"] = "pointer";
bild.style["overflow"] = "hidden";
bild.style["text-indent"] = "100%";
bild.style["white-space"] = "nowrap";
container.style["position"] = "relative";
container.style["font-family"] = "Arial";
text.style["position"] = "center";
text.style["bottom"] = "5px";
text.style["left"] = "1px";
text.style["color"] = "white";

Overriding !important style

Title pretty much sums it up.
The external style sheet has the following code:
td.EvenRow a {
display: none !important;
}
I have tried using:
element.style.display = "inline";
and
element.style.display = "inline !important";
but neither works. Is it possible to override an !important style using javascript.
This is for a greasemonkey extension, if that makes a difference.
There are a couple of simple one-liners you can use to do this.
Set a "style" attribute on the element:
element.setAttribute('style', 'display:inline !important');
or...
Modify the cssText property of the style object:
element.style.cssText = 'display:inline !important';
Either will do the job.
===
I've written a jQuery plugin called "important" to manipulate !important rules in elements, : http://github.com/premasagar/important
===
Edit:
As shared in the comments, the standard CSSOM interface (the API for JavaScript to interact with CSS) provides the setProperty method:
element.style.setProperty(propertyName, value, priority);
E.g:
document.body.style.setProperty('background-color', 'red', 'important');
element.style has a setProperty method that can take the priority as a third parameter:
element.style.setProperty("display", "inline", "important")
It didn't work in old IEs but it should be fine in current browsers.
I believe the only way to do this it to add the style as a new CSS declaration with the '!important' suffix. The easiest way to do this is to append a new <style> element to the head of document:
function addNewStyle(newStyle) {
var styleElement = document.getElementById('styles_js');
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = 'styles_js';
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
styleElement.appendChild(document.createTextNode(newStyle));
}
addNewStyle('td.EvenRow a {display:inline !important;}')
The rules added with the above method will (if you use the !important suffix) override other previously set styling. If you're not using the suffix then make sure to take concepts like 'specificity' into account.
Building on #Premasagar's excellent answer; if you don't want to remove all the other inline styles use this
//accepts the hyphenated versions (i.e. not 'cssFloat')
addStyle(element, property, value, important) {
//remove previously defined property
if (element.style.setProperty)
element.style.setProperty(property, '');
else
element.style.setAttribute(property, '');
//insert the new style with all the old rules
element.setAttribute('style', element.style.cssText +
property + ':' + value + ((important) ? ' !important' : '') + ';');
}
Can't use removeProperty() because it wont remove !important rules in Chrome.
Can't use element.style[property] = '' because it only accepts camelCase in FireFox.
If you want to update / add single style in DOM Element style attribute you can use this function:
function setCssTextStyle(el, style, value) {
var result = el.style.cssText.match(new RegExp("(?:[;\\s]|^)(" +
style.replace("-", "\\-") + "\\s*:(.*?)(;|$))")),
idx;
if (result) {
idx = result.index + result[0].indexOf(result[1]);
el.style.cssText = el.style.cssText.substring(0, idx) +
style + ": " + value + ";" +
el.style.cssText.substring(idx + result[1].length);
} else {
el.style.cssText += " " + style + ": " + value + ";";
}
}
style.cssText is supported for all major browsers.
Use case example:
var elem = document.getElementById("elementId");
setCssTextStyle(elem, "margin-top", "10px !important");
Here is link to demo
If all you are doing is adding css to the page, then I would suggest you use the Stylish addon, and write a user style instead of a user script, because a user style is more efficient and appropriate.
See this page with information on how to create a user style
https://developer.mozilla.org/en-US/docs/Web/CSS/initial
use initial property in css3
<p style="color:red!important">
this text is red
<em style="color:initial">
this text is in the initial color (e.g. black)
</em>
this is red again
</p>
https://jsfiddle.net/xk6Ut/256/
One option to override CSS class in JavaScript is using an ID for the style element so that we can update the CSS class
function writeStyles(styleName, cssText) {
var styleElement = document.getElementById(styleName);
if (styleElement) document.getElementsByTagName('head')[0].removeChild(
styleElement);
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = styleName;
styleElement.innerHTML = cssText;
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
..
var cssText = '.testDIV{ height:' + height + 'px !important; }';
writeStyles('styles_js', cssText)
Rather than injecting style, if you inject a class(for eg: 'show') through java script, it will work. But here you need css like below. the added class css rule should be below your original rule.
td.EvenRow a{
display: none !important;
}
td.EvenRow a.show{
display: block !important;
}
There we have another possibility to remove a property value from the CSS.
Like using the replace method in js. But you have to know exactly the ID of the style, or you can write a for loop to detecting that by (count styles on the page, then check if any of those 'includes' or 'match' an !important value. & you can count also - how much contains them, or just simply write a global [regexp: /str/gi] replacing method)
Mine is very simple, but I attach a jsBin, for example:
https://jsbin.com/geqodeg/edit?html,css,js,output
First I set the body background in CSS for yellow !important, then I overrided by JS for darkPink.
Below is a snippet of code to set the important parameter for the style attribute using jquery.
$.fn.setFixedStyle = function(styles){
var s = $(this).attr("style");
s = "{"+s.replace(/;/g,",").replace(/'|"/g,"");
s = s.substring(0,s.length-1)+"}";
s = s.replace(/,/g,"\",\"").replace(/{/g,"{\"").replace(/}/g,"\"}").replace(/:/g,"\":\"");
var stOb = JSON.parse(s),st;
if(!styles){
$.each(stOb,function(k,v){
stOb[k] +=" !important";
});
}
else{
$.each(styles,function(k,v){
if(v.length>0){
stOb[k] = v+" !important";
}else{
stOb[k] += " !important";
}
});
}
var ns = JSON.stringify(stOb);
$(this).attr("style",ns.replace(/"|{|}/g,"").replace(/,/g,";"));
};
Usage is pretty simple.Just pass an object containing all the attributes you want to set as important.
$("#i1").setFixedStyle({"width":"50px","height":""});
There are two additional options.
1.To just add important parameter to already present style attribute pass empty string.
2.To add important param for all attributes present dont pass anything. It will set all attributes as important.
Here is it live in action. http://codepen.io/agaase/pen/nkvjr

Categories

Resources