Applying CSS style to dynamically created DIV - javascript

I successfully created a div dynamically.
But i was wondering is there a way to apply CSS style directly instead of applying style one by one using Javascript.

DEMO FIDDLE
You should use the className property:
divTag.className = "divdrag";
The div now has the appropriate class name and you just need to add all of your styling to that CSS class.
More info here

Add
divTag.classList.add("divdrag");
or
divTag.className += "divdrag";

Use cssText for apply multiple css to created dynamic div.
divTag.style.cssText="align:center; border:1px solid #ccc; margin-top:20px; margin-bottom:20px;";
Updated
Or use simple css based on div1 id
#div1{
align:center;
border:1px solid #ccc;
margin-top:20px;
margin-bottom:2px;
}
Note you should create the id by
divTag.id = "div1";

you set the classes with this..
if (divTag.classList) {
el.classList.add("divdrag");
}
else {
divTag.className += ' ' + "divdrag";
}

Related

About js to Get background Color

i have a question about to get the X id by
document.getElementById("X").style.backgroundColor
this is my HTML:
<div id ="X" class="main-sidebar text-white ">
</div>
CSS like:
.main-sidebar{
background-color: #343a40;
width:10%;
height:100%;
display:block;
position: absolute;
left:0px;
/*top:0px;*/
}
But when I use document.getElementById("X").style.backgroundColor in js i get NULL value...
That's because style refers to the inline style attribute in your HTML. If you want to get the style that's set via CSS only, you will need to use computedStyles.
const elem = document.getElementsByTagName('p')[0]; // get element
const styles = window.getComputedStyle(elem); // get computed style of element
console.log(styles.getPropertyValue('background-color')); // get specific attribute
p {
background-color: red;
}
<p>Hi!</p>
Try using computed styles:
window.getComputedStyle(document.getElementById("X")).backgroundColor
.style Will get or set the inline style of an element.
In your case, the style for .main-sidebar is in a .css file.
What you can do is use getComputedStyle():
getComputedStyle(document.getElementById("X")).backgroundColor // #343a40

css style change for table using button/jquery

Here's the issue:
I want to be able to turn "on and off" the grid on this html table. I'm not sure why the css is not taking over other than the original css I have for the table isn't allowed to change.
Here's the fiddle
Here's the css:
td{ width:15px; height:15px; font-size: 10px; text-align:center; vertical-align:middle; border-style:inset; text-overflow:ellipsis; white-space: nowrap; z-index:-1;}
and here's the jquery:
$('#hideGrid').click(function(){
$('#tab td').css({ 'border-style': 'none !important'});
});
$('#showGrid').click(function(){
$('#tab.td').css({'border-style': 'inset !important'});
});
Any advice on how to get the css with the button to override the declared original css or explain why this method is not working?
Thanks!
Use CSS class it is fatser than .css(). Aslo not that in you fiddle you have not set ID of table.
HTML
<table id="tab">
CSS, Here created a new class
td.no-border {
border-style:none;
}
JS
$('#hideGrid').click(function () {
$('#tab td').addClass('no-border'); //Added class
});
$('#showGrid').click(function () {
$('#tab td').removeClass('no-border'); //Removed class
});
DEMO
works now:
http://jsfiddle.net/Nez7V/2/
your selector for the table td's was wrong:
$(document).ready(function(){
var tableTds = $('table td');
$('#hideGrid').click(function(){
tableTds.css('border-style', 'none');
});
$('#showGrid').click(function(){
tableTds.css('border-style', 'inset');
});
});
however, you can use the jquery function elem.css(attribute, value) if you only want to change one css-attribute.

table clicked cell color scheme

I have menu in a table "mytable" like this:
<td id="1" align="center" onclick="clicked(1);"> one </td >
<td id="2" align="center" onclick="clicked(2);"> two </td >
<td id="3" align="center" onclick="clicked(3);"> three </td>
<td id="4" align="center" onclick="clicked(4);"> four </td>
...
The css:
#mytable {
background:#d0d0df;
cursor:pointer;
}
#mytable td{
background:#4092c4;
color:#efefef;
}
#mytable td:hover{
background:#e0e0e0;
color:#FF004F;
}
The javascript:
function clicked(k){
for (x=1; x<5; x++){ // reset all cells
document.getElementById(x).style.background='#4092c4';
document.getElementById(x).style.color='#efefef';
}
// set cell
document.getElementById(k).style.background='#106284';
document.getElementById(k).style.color='#FF004F';
}
How to highlight a single clicked cell and maintain the hover functionality?
The above code works, but after calling clicked() the hovering functionality is lost.
I rather not use jquery.
Syntax issue, ids that are just numbers are not valid HTML.
The problem you are having is that when the javascript runs, it appends the styles inline on the elements, and the CSS styles cannot override inline (not without adding things like !important, and that just gets ugly).
I would steer away from writing styling in the JS, just use it to change classes. So make a new class, lets call it .active, and when you click a tablecell just add the class, and remove the class from all the others.
Something like (this is example only, some tweaking may be required)
function clicked(k){
var otherCell, thisCell;
for (x=1; x<5; x++){ // reset all cells
otherCell = document.getElementById(x);
otherCell.className = otherCell.className.replace('active','');
}
// set cell as active
thisCell = document.getElementById(k);
thisCell.className += thisCell.className + ' active';
}
and then set the styles only in css, something like
#mytable {
background:#d0d0df;
cursor:pointer;
}
#mytable td{
background:#4092c4;
color:#efefef;
}
#mytable td.active{
background:#106284;
color:#efefef;
}
#mytable td:hover{
background:#e0e0e0;
color:#FF004F;
}
This way you have more control over the 'cascading' of the style rules, being more specific or changing the order of the rules will give you possible different outcomes.
As per fiddle here
This is probably overkill, but the jQuery javascript library makes this trivial.
I've channged the HTML too becuase using table for non-tabula data should be avoided.
New HTML:
<ul id="mytable">
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
Also note, no ID's on the items and no in-line javascript, nice and clean.
New CSS:
#mytable {
background:#d0d0df;
cursor:pointer;
list-style:none;
padding-left:0;
}
#mytable li {
background:#4092c4;
color:#efefef;
display:inline-block;
margin:2px -2px 2px 2px;
padding:3px;
}
#mytable li:hover {
background:#e0e0e0;
color:#FF004F;
}
#mytable li.active {
background:#106284;
color:#efefef;
}
Note: I've used inline-block for the list items to orientate the horizontaly, you could also use float or table-cell. This is a good article on floats vs inline-blocl. Also note the new active class.
Now for the super-simple jquery (make sure to include the jquery library!)
$(document).ready(function(){ //Performs the following code when the document is fully loaded
//Assigns a click event handler to list items in an element with ID "myTable"
$("#mytable li").click(function () {
//Remove the active class from list items in #mytable that were not clicked
$("#mytable li").not($(this)).removeClass("active");
//Add the active class to the clicked element.
$(this).addClass("active");
});
});
Fiddle
Just make sure to include the jquery library and to use $(document).ready();
Handy jQuery Links
Document Ready
Selectors
Click
Not
Add Class
Remove Class

Created div elements' random margins not working

Problem and source code
I'm trying to create <div>s within another <div> at the click of a button. When the button is clicked, a new inner <div> is created (within the outer <div>) with a unique id. I have this part working but here's where I'm running into an issue: I want each inner <div> to have a random margin-top.
Javascript
function pressButton() {
number += 1;
makeDiv(number);
};
function makeDiv(x) {
var innerDiv = document.createElement("innerDiv" + x);
outer.appendChild(innerDiv);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + ";display:inline-block;width:48px;height:48px;background-color:#000;");
};
CSS:
#outer {
position:absolute;
white-space:nowrap;
height:118px;
overflow:auto;
width:100%;
padding:2px;
}
Result (after button is clicked 4 times)
<div id="outer">
<innerDiv1 style="margin-top:15;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv1>
<innerDiv2 style="margin-top:23;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv2>
<innerDiv3 style="margin-top:37;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv3>
<innerDiv4 style="margin-top:0;display:inline-block;width:48px;height:48px;background-color:#000;"></innerDiv4>
</div>
The result (which I got from inspecting the inner elements in my browser) looks like everything worked - all the margin-tops are random like I wanted. However, the visual result is this:
As you can see, the black inner <div>s all have the same margin-top. What am I doing wrong? How can I make the created <div>s all have random margin-tops?
The CSS spec requires that a length (other than zero) that is missing a unit be treated as an error (and thus ignored). Therefore, add px to the end of your generated margin number, and all should be well.
Live Demo
Description
This happens, because you set the display:inline-block; property. This makes them all to be in one line, so they will allign to the innerDivx that has the highest margin-top.
Delete the display:inline-block; property and give them float:left;. If you want to keep the gap between them, also add margin-left:5px;. And don't forget that margin-top's value needs a unit. I think you wanted to use px.
Also <innerDivx> is not a valid HTML tag. You should change them to a <div> and use innerDivx as an id attribute. Also your tags use almost the same CSS styles so you should put the same ones to a class and add the class instead.
Full solution code
HTML
<button id="button1">Add box</button>
<div id="outer"></div>
JavaScript
var number = 0;
document.getElementById("button1").addEventListener("click", pressButton, false);
function pressButton() {
++number;
makeDiv(number);
};
function makeDiv(x) {
var innerDiv = document.createElement("div");
outer.appendChild(innerDiv);
innerDiv.className += " box";
innerDiv.setAttribute("id", "innerDiv" + x);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
};
CSS
#outer {
position: absolute;
white-space: nowrap;
height: 118px;
overflow: auto;
width: 100%;
padding: 2px;
}
.box {
float: left;
width: 48px;
height: 48px;
background-color: #000;
margin-left: 5px;
}
This is likely caused by the position model used for inline-block elements - they're all being vertically-aligned at their bottom line in a row.
I suggest that you simplify this and use position: block with float: left
http://jsfiddle.net/2y5bJ/4/
I also suggest that you stick to standard elements to ensure cross-browser compatibility - don't create your own elements called innerDiv1 etc, but use div elements with unique IDs.
function makeDiv(x) {
var innerDiv = document.createElement("div");
outer.appendChild(div);
innerDiv.setAttribute('id', 'innerDiv' + x);
innerDiv.setAttribute("style", "margin-top:" + Math.floor(Math.random()*51) + "px;");
};
I think there is no tag available with name
<innerDiv1>
This may be the cause.

How to add dynamic css class with active property attached to button

How to add following css class dynamically to a button.
.custom-button:active{
background-image: url('images/pressed.jpg') !important;
}
i created a lot of buttons in java-script using the following code. The buttons already have a class .custom-button button without the property (active).
var ItemsToAdd = '';
ItemsToAdd += '<a id="' + id + '" data-role="button" style="background-image:url('+ img_path_normal +');border-width:0px;" class="custom-button" ></a>';
$("#container2").append(ItemsToAdd);
the class that i already added using java script is following:
.custom-button {
height: 150px !important;
width: 120px;
background-size:100% 100%;
border:0px;
border-radius:0px;
border-style:none;
padding:0px;
margin:0px;
border-width:0px;
}
You can use addClass() to add any class to an HTML element.
Set up the CSS you want to add like so:
.custom-button-active{
background-image: url('images/pressed.jpg') !important;
}
Notice I changed it to .custom-button-active, so it doesn't use a pseudo class (since there is no need for it). Now, when you want this style to apply to a button simply add that class to the button.
button.addClass('custom-button-active');
Now, the button will have that class in addition to any other classes you already gave it, and will use the appropriate styles.
As it was stated above, you can't directly work with pseudo-classes in JavaScript. However, you can just change your stylesheet from inside Javascript code. Something like this:
document.styleSheets[0].insertRule('.custom-button:active { background-image: url('images/pressed.jpg') !important; }', 0);
document.styleSheets[0].cssRules[0].style.backgroundColor= 'red';
or
var element = document.createElement('style');
document.head.appendChild(element);
var s = element.sheet;
s.insertRule('.custom-button:active {background-image: url("images/pressed.jpg") !important;}', s.cssRules.length);
More information about that syntax here: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet.insertRule

Categories