adding css styles to dynamically added <form> elements in java script - javascript

I used the following code (Javascript) to dynamically load elements into "Mobile Webpage". It works fine but i can't set CSS styles(like height,width...) to those newly added elements.
here by this code buttons are loaded perfectly .
in this i am unable to vary the size of dynamically loaded button using css elements.
<head>
<script type="text/javascript">
var arrayToModify = [];
window.onload = function () {
var i, MyArray, ButtonContainer, NewButton;
MyArray = ["Option 1","Option 2","Option 3","Option 4","Option 5"];
ButtonContainer = document.getElementById("Button_holder");
for (i = 0; i < MyArray.length; i++) {
NewButton = document.createElement('input');
NewButton.type = 'button';
NewButton.value = MyArray[i];
NewButton.id = MyArray[i];;
NewButton.onclick = function () {
alert('You Clicked '+this.id);
arrayToModify[arrayToModify.length] = this.id;
};
ButtonContainer.appendChild(NewButton);
}
};
</script>
<style>
NewButton
{
width:100%;
height:120px;
background-color:red;
}
ButtonContainer
{
width:100%;
height:120px;
background-color:yellow;
}
.divclass
{
height:400px;
background-color:lightblue;
}
</style>
</head>
<body>
<div id="Button_holder" class="divclass">
</div>
<input type='button' onclick='alert(arrayToModify);' class="ntl" value='Vote' />
</body>
</html>

Your CSS is wrong. CSS doesn't look at JS variable names. So your CSS selectors are looking for those HTML tags (i.e. an HTML tag <NewButton>, which obviously doesn't exist).
Instead, try adding a class to each of your new inputs and button container, and then prefix your CSS selectors with a . (which is a class selector).
Here is an example: jsFiddle Demo
HTML:
<div id="Button_holder" class="divclass ButtonContainer"> <!-- added a class name here -->
</div>
<input type='button' onclick='alert(arrayToModify);' class="ntl" value='Vote' />
CSS:
.NewButton
{
width:100%;
height:120px;
background-color:red;
}
.ButtonContainer
{
width:100%;
height:120px;
background-color:yellow;
}
.divclass
{
height:400px;
background-color:lightblue;
}
JS:
var arrayToModify = [];
window.onload = function () {
var i, MyArray, ButtonContainer, NewButton;
MyArray = ["Option 1","Option 2","Option 3","Option 4","Option 5"];
ButtonContainer = document.getElementById("Button_holder");
for (i = 0; i < MyArray.length; i++) {
NewButton = document.createElement('input');
NewButton.type = 'button';
NewButton.value = MyArray[i];
NewButton.id = MyArray[i];
NewButton.className = 'NewButton'; // added a class name here
NewButton.onclick = function () {
alert('You Clicked '+this.id);
arrayToModify[arrayToModify.length] = this.id;
};
ButtonContainer.appendChild(NewButton);
}
};
And, as #SurrealDreams said, it would be a good idea to keep your CSS in an external file to make it easier to maintain and reuse. Suppose you had multiple pages with the exact same styles? Instead of rewriting these styles every time, just put them in an external .css file and then include that file in your <head> using something like <link rel="stylesheet" type="text/css" href="path/to/your/css/file.css" />.
I would really suggest you go through a CSS tutorial. For this specific problem, this section should prove useful.

What are NewButton and ButtonContainer in css? It looks written as tags. If you need those as classes, you should set . before each, e.g. .NewButton.
Updated code:
<head>
<script type="text/javascript">
var arrayToModify = [];
window.onload = function () {
var i, MyArray, ButtonContainer, NewButton;
MyArray = ["Option 1","Option 2","Option 3","Option 4","Option 5"];
ButtonContainer = document.getElementById("Button_holder");
for (i = 0; i < MyArray.length; i++) {
NewButton = document.createElement('input');
NewButton.type = 'button';
NewButton.value = MyArray[i];
NewButton.className = 'NewButton';
NewButton.id = MyArray[i];;
NewButton.onclick = function () {
alert('You Clicked '+this.id);
arrayToModify[arrayToModify.length] = this.id;
};
ButtonContainer.appendChild(NewButton);
}
};
</script>
<style>
.NewButton
{
width:100%;
height:120px;
background-color:red;
}
.ButtonContainer
{
width:100%;
height:120px;
background-color:yellow;
}
.divclass
{
height:auto;
background-color:lightblue;
}
</style>
</head>
<body>
<div id="Button_holder" class="divclass">
</div>
<input type='button' onclick='alert(arrayToModify);' class="ntl" value='Vote' />
</body>
</html>

Your approach has been to assign CSS styles to the names of JavaScript variables/objects. There's no direct connection between the two - CSS is looking for HTML elements with tags named ButtonContainer and NewButton. CSS isn't "smart" - it's not going to map the HTML generated by JavaScript to the styles. It's looking for a simple match, so you need to design the code so it has a match.
To answer your question as asked, you could include a line like this...
NewButton.style = "width: 20px; height: 40px; border: 1px solid #000;";
This will set styles on each generated NewButton element. Using CSS classes will give you a better overall result.
Please note - there's a better approach.
In general, the best approach is to create your code with classes and ids as part of the code. Include CSS rules in your general CSS files to style those elements.
While you can add style to generated code, it's best to keep all your styling in the CSS files. It's much easier to maintain that way. It's all in one place, and a typo won't break your scripts. CSS is much more tolerant of errors. Inline styles are best avoided, just like it's best to avoid JavaScript written inside HTML elements.

In Javascript, you can add css Class like this:
For instance:
document.getElementById("your-ID").setAttribute("class", "your-className");
Try like this.
EDIT: As Travesty3 mentioned you're missing the add . for class selector in css. Once you correct mistake, you can use the above approach to add the classes.
ButtonContainer.setAttribute("class", "ButtonContainer");
NewButton.setAttribute("class", "NewButton");
Add the above two lines at the last of your JS code. check this Updated JSFiddle in this I've reduced the remove the height and width of the button to show difference.

Related

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>

How to dynamically add a CSS class and implement its style in JavaScript

Hi I'm new to JavaScript and CSS and I would like to create a JavaScript function that dynamically applies the style properties that are defined inside this function to a specific element.
Please check my code below, I have managed to create the element and add the class to that element but I'm struggling to implement the style properties inside this function.
function highlight(){
var styl = document.querySelector("#element_to_pop_up");
styl.style.cssText = " background-color:#fff;border-radius:15px; color:#000;display:none;padding:20px;min-width:30%;min-height: 30%;max-width:40%; max-height: 40%;";
styl.className = styl.className + "b-close";
//.b-close{
//cursor:pointer;
//position:absolute;
//right:10px;
//top:5px;
//}
}
Please any help will be highly appreciated.
If you want to add a style class to your page and write its style content, you should create it first then put it in a <style> tag, so you can use it later.
This is your way to go:
function highlight() {
var styl = document.querySelector("#element_to_pop_up");
//Create StyleSheet
var styleSheet = document.createElement("style");
var text = document.createTextNode("\n.b-close {\n cursor:pointer;\n position:absolute;\n right:10px;\n top:5px;\n}");
//Put the style on it.
styleSheet.appendChild(text);
//Append it to <head>
document.head.appendChild(styleSheet);
//Apply it
styl.className = styl.className + " b-close";
}
<div onclick="highlight()" id="element_to_pop_up">bla bla bla</div>
Create a Style Sheet Element.
Put the style on it.
Append it to the head of the document.
Use this style or apply it to element.
EDIT:
If you will pass the style top and right values as parameters to the function just do the following:
function highlight(right, top) {
var styl = document.querySelector("#element_to_pop_up");
var styleSheet = document.createElement("style");
var text = document.createTextNode("\n.b-close {\n cursor:pointer;\n position:absolute;\n right: "+right+"px;\n top: "+top+"px;\n}");
styleSheet.appendChild(text);
document.head.appendChild(styleSheet);
styl.className = styl.className + " b-close";
}
Use jquery insted on javascript.
$(selector).css("width":"100%").css("height","100px");
You can just add a CSS class (and style it in your stylesheet instead of your javascript).
Here is an example (there are multiple way to do it but I don't know what your try to achieve exactly) :
function highlight(){
var target = document.getElementById("header");
target.className = target.className + " highlighted";
}
var btn = document.getElementById('add-class');
btn.addEventListener('click', highlight);
.highlighted {
/*Your CSS*/
background-color: red;
}
<h1 id="header">Lorem</h1>
<button id="add-class">Click me</button>
Edit: If you want to use jQuery, it's even simpler :
$(document).ready(function() {
$('#add-class').on('click', function() {
$('#header').toggleClass('highlighted');
});
});
.highlighted {
/*Your CSS*/
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="header">Lorem</h1>
<button id="add-class">Click me</button>

Best way to show all hidden divs in javascript

I have several hidden divs inside large div, they can be shown one by one or all at once
It looks like this:
<div class="maindiv">
Print "<a href=javascript:show()>Click here to show all</a>
Show/hide div1
<div id="div1" style="display:none;">.....</div>
Show/hide div2
<div id="div2" style="display:none;">.....</div>
....
</div>
showhide() function is ok showing/hiding given div, show() works too but like this:
function show(){
div1.style.display="block";
div2.style.display="block";
...
}
so if I'll have 100 divs I'll have to enter it there 100 times
so my question is, how can I find all hidden divs in div with class maindiv and show em other way than enumerate? Or is the way I do ok?
Try using a generic css class name that is defined similarly:
.hidden{
display:none;
}
Then all you have to do is select the elements that have that class and remove that class. Assuming you are using at least IE9 you can try:
var divs = document.getElementsByClassName("hidden");
for(var i = 0; i < divs.length; i++)
{
divs[i].className = ""; //assuming you only have that class set else you will need to do a search and replace
}
If you have to support earlier versions there are other methods that will work to gather all the divs you need such as document.getElementsByTagName("div")
LIVE DEMO
Try this:
JQuery
$('.maindiv div a').click(function(){
$(this).next().toggle();
});
$('#showAll').click(function(){
$('.maindiv div div').show();
});
HTML
<div class="maindiv">
Click here to show all
<div>
Show/hide div1
<div>.....</div>
Show/hide div2
<div>.....</div>
</div>
</div>
CSS
.maindiv div a{
display:block;
}
.maindiv div div{
display:none;
}
Please try with the below code snippet.
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
//You can also write here if condition
divs[i].style.display = "block";
}
I think this can work
http://jsfiddle.net/rtu75/
function show() {
var divs = document.getElementsByClassName("maindiv");
var l = divs.length;
for( var i = 0; i < l; i++) {
divs[i].setAttribute("class", "show");
}
}
In your css
.show div {
display: block !important;
}
Added important since you have inline styles
Using jQuery, try
$("*").show();
or
$(parentElem).find("*").show();
or
$(":not(:visible)").show();
// This selects "*". Not I expected.
See w3 - css selectors, MDN - css pseudo classes, and jQuery $(), $().find(), $().filter() methods.
As I saw your code below, I saw it's almost work. You need to change id='div1' to class='hid' after that read my below step >> Go down
Show/hide div1
<div id="div1" style="display:none;">.....</div>
Here is my step, I am in same problem but now I can solve this because I read https://stackoverflow.com/a/24192071/10618118 then try to solve until done.
Read below,it's my code.It's work as I want.
in My Style for CSS be like this
<style>
.hid {}
</style>
Next is My Button to control it hidden or visible, Simple.
<button id="see" type="button" onclick="clickSee();">Show More ...</button>
Next step, look at my Javascript Code below,
I use JQuery 3.2.1 to change function in onclick of button.
when user want to hide or see more
just click Show More ... or ... Show less,
Actually it's the same button but user don't know.
If you didn't use JQuery yet and decide to use just copy
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
and paste in <head></head>
<script>
function clickSee() {
document.getElementById("see").innerHTML = "... Show Less";
var divs = document.getElementsByClassName("hid");
for (var i = 0; i < divs.length; i++){
divs[i].style.display = "block";
}
//I use JQuery
$("#see").attr("onclick", "clickHide()");
}
function clickHide() {
document.getElementById("see").innerHTML = "Show More ... ";
var divs = document.getElementsByClassName("hid");
for (var i = 0; i < divs.length; i++){
divs[i].style.display = "none";
}
//I use JQuery
$("#see").attr("onclick", "clickSee()");
}
</script>
If you have any issues just comment below, I will try to help because when done.
There are many way to make your idea work. but I see here is my basic way.
Feel free for new recommendation. Thank you.

Is there any way to change CSS Class that registered in browser

I explain the problem by a simple example.
I have the following html page. It's simple.
There is one CSS Class named TestDiv and two javascript function.
addDiv creates new div and appends it to page by clicking on button "add new div".
setBlue is the function that i want to change the color of divs that has class TestDiv and I dont know how.
You can see that i wrote some code to change the current generated Divs inside the setBlue function. But I don't know how i can change the class to affect the new divs that will generated by addDiv function after that.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.TestDiv {
color:red;
}
</style>
<script>
function addDiv() {
var newDiv = document.createElement("div")
newDiv.className = "TestDiv";
newDiv.innerHTML = "test";
document.getElementById("firstDiv").insertBefore(newDiv);
}
function setBlue() {
var currentDivList=document.getElementsByClassName("TestDiv");
for(var i=0;i<currentDivList.length;i++){
currentDivList[i].style.color = "blue";
}
// What i can write here to change the TestDiv css class
// And after that, new (div)s will generate by new color(changed css class)
}
</script>
</head>
<body>
<div id="firstDiv" class="TestDiv">
test
</div>
<input type="button" value="add new div" onclick="addDiv();"/>
<input type="button" value="change color to blue" onclick="setBlue();"/>
</body>
</html>
I don't recommend adding or modifying CSS rules on-the-fly, but there are several solutions:
Modify the original CSS rule
<style id="myStyle">
.TestDiv {
color:red;
}
</style>
...
var myStyle = document.getElementById("myStyle");
myStyle.sheet.cssRules.item(0).cssText = ".TestDiv { color: blue }";
(I had to assign an ID to the style tag because I couldn't get it work in the jsFiddle environment otherwise. It should equally be possible by using document.styleSheets[0].)
Add a CSS rule to a newly created style sheet (thanks to pawel!)
var style = document.createElement('style');
document.head.appendChild(style);
style.sheet.addRule(".TestDiv", "color: blue");
Add raw CSS text to a newly created style sheet:
→ jsFiddle
var sheet = document.createElement('style')
sheet.innerHTML = ".TestDiv { color: blue }";
document.body.appendChild(sheet);
style.color creates an inline style that overrides the class styles. In order to retain whether setBlue() has been clicked store a var either isBlue = false or divClass = 'blue'/'red' and toggle a class on all the divs which retains your color styles:
http://jsbin.com/IdadUz/1/edit?html,css,js,output
You cannot directly modify style elements that have been created on the page or in external Style Sheets, one way to do this would be with the following javascript :
var newColor = '';
function addDiv() {
var newDiv = document.createElement("div")
newDiv.className = "TestDiv";
newDiv.innerHTML = "test";
document.getElementById("firstDiv").insertBefore(newDiv);
if (newColor != '') {
newDiv.style.color = newColor;
}
}
function setBlue() {
var currentDivList = document.getElementsByClassName("TestDiv");
for (var i = 0; i < currentDivList.length; i++) {
currentDivList[i].style.color = "blue";
}
newColor = 'blue';
}
When you click on the Change Color button it will set the newColor variable to blue. Then when you add a new div it will check if this variable has been set, if so it will change the style.
Example JSFiddle
I'd suggest adding a stylesheet to the head section:
function setBlue() {
var currentDivList=document.getElementsByClassName("TestDiv");
for (var i=0; i < currentDivList.length; i++) {
currentDivList[i].style.color = "blue";
}
var head = document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.innerHTML = ".TestDiv { color: blue; }";
head.appendChild(style);
}

IE9 get hover color javascript [duplicate]

I made a function that overwrite the the :hover of some elements on a page. It fades between the normal and the :hover effect. That for i had to create a .hover class in my CSS file. I think this is a little unclean. How could i read the the :hover pseudo class contents?
Using getComputedStyle as on the accepted answer won't work, because:
The computed style for the hover state is only available when the element is actually on that state.
The second parameter to getComputedStyle should be empty or a pseudo-element. It doesn't work with :hover because it's a pseudo-class.
Here is an alternative solution:
function getCssPropertyForRule(rule, prop) {
var sheets = document.styleSheets;
var slen = sheets.length;
for(var i=0; i<slen; i++) {
var rules = document.styleSheets[i].cssRules;
var rlen = rules.length;
for(var j=0; j<rlen; j++) {
if(rules[j].selectorText == rule) {
return rules[j].style[prop];
}
}
}
}
// Get the "color" value defined on a "div:hover" rule,
// and output it to the console
console.log(getCssPropertyForRule('div:hover', 'color'));
Demo
You could access document.styleSheets and look for a rule that is applied on that specific element. But that’s not any cleaner than using a simple additional class.
UPDATE: I somehow got this wrong. The below example doesn't work. See #bfavaretto's comment for an explanation.
In Firefox, Opera and Chrome or any other browser that correctly implements window.getComputedStyle is very simple. You just have to pass "hover" as the second argument:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
div {
display: block;
width: 200px;
height: 200px;
background: red;
}
div:hover {
background: green;
}
</style>
</head>
<body>
<div></div>
<script type="text/javascript">
window.onload = function () {
var div = document.getElementsByTagName("div")[0];
var style = window.getComputedStyle(div, "hover");
alert(style.backgroundColor);
};
</script>
</body>
</html>
But I don't believe there's yet a solution for Internet Explorer, except for using document.styleSheets as Gumbo suggested. But there will be differences. So, having a .hover class is the best solution so far. Not unclean at all.
If there are any people here who use the questions accepted answer but it won't work, here's a nice function that might:
function getPseudoStyle(id, style) {
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
var targetrule = "";
if (all[i].id === id) {
if(all[i].selectorText.toLowerCase()== id + ":" + style) { //example. find "a:hover" rule
targetrule=myrules[i]
}
}
return targetrule;
}
}
There is an alterantive way to get :hover pseudo class with javascript. You can write your styles of hover pseudo class in a content property.
p::before,
p::after{
content: 'background-color: blue; color:blue; font-size: 14px;';
}
then read from it via getComputedStyle() method:
console.log(getComputedStyle(document.querySelector('p'),':before').getPropertyValue('content'));

Categories

Resources