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

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

Related

Clear inline style after reset

How do I remove the inline style which is added by JavaScript?
For example: if people click the button, the marginTop of div#test will be 30px, but what if I want to remove the inline style instead of resetting it to another value like 0?
I do not want to add a class to that element and remove it because it's not suitable in my use case.
const elm = document.querySelector('#test')
function change() {
elm.style.marginTop = '30px';
}
#test {
width: 150px;
height: 60px;
background-color: blue;
}
<div id="test"></div>
<button onclick="change()">Change</button>
either set as empty string
elm.style.marginTop = '';
or to remove the complete attribute use
removeAttribute
elem.removeAttribute('style');

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

How to change class named active into link's active attribute in javascript

I'm using superfish for menu.Since it doesn't come with active class to denote current page tab.I added the following javascript.
<script type="text/javascript">
var path = window.location.pathname.split('/');
path = path[path.length-1];
if (path !== undefined) {
$("ul.sf-menu")
.find("a[href$='" + path + "']") // gets all links that match the href
.parents('li') // gets all list items that are ancestors of the link
.children('a') // walks down one level from all selected li's
.addClass('active');
}
</script>
I also added a class named active in css as the script requires.
.sf-menu a.active{
margin-top:-5px;
height: 51px;
padding-top: 15px;
z-index: 100;
background-color:#072438;
}
It worked just fine.However for some reason I would like to change the css from
a.active into a:active
But how do I change this part in javascript to suit the css please?
.addClass('active');
You can't add a pseudo-class on an element using javascript in the same way that you can't add a pseudo-class in an inline style='' attribute.
What you can do is alter your stylesheet with javascript to add the rule you want:
document.styleSheets[0].insertRule('a:active { color: red; }', 0);

click to change background toggle

When I click on it changes background. It works fine. But what if I want to click on it again to restore the original background? I have this code:
jQuery(document).ready(function($) {
$(".select").on("click", function () {
$(this).css("background-image", "url(images/selected.png)");
});
});
Here is jsfiddle EXAMPLE
Basically when I click on the div it changes the background, which is fine. But I want to have ability to click on it again to restore the original background.
It will be an alternative solution for tick box, but just for demo purposes.
Thanks
JS
replace
$(this).css("background-image", "url(images/selected.png)");
with
$(this).toggleClass("active");
Style
#multiselect .active {
background-image: url('...');
}
Fiddle http://jsfiddle.net/09xgrhxo/4/
Instead of using .css() to change the background-image I would add a class in your CSS and use .toggleClass().
Also be aware that simply adding a class will not be specific enough because your css is using:
#multiselect .select
you're going to have to target the class you add as a child of #multiselect:
#multiselect .change
CSS
#multiselect .change{
background-image: url(http://t2.gstatic.com/images?q=tbn:ANd9GcSZ51HqKXkejWAFcSBrodHd5eUN2QaIJro0jhN1YpmljSdQ5dj2)
}
JS
$(".select").on("click", function () {
$(this).toggleClass("change");
});
FIDDLE
You could use data-* attribute.
$('.select').attr('data-img', $('.select').css('background-image'));
$(".select").on("click", function() {
$(this).css("background-image", ($(this).css('background-image') == $(this).data('img')) ? "url(http://t2.gstatic.com/images?q=tbn:ANd9GcSZ51HqKXkejWAFcSBrodHd5eUN2QaIJro0jhN1YpmljSdQ5dj2)" : $(this).data('img'));
});
#multiselect .select {
background: url(http://t0.gstatic.com/images?q=tbn:ANd9GcQF_ErOlc78eOGZaEWb-dwPkrv2uyAoKx0Pbn3-e0tAZoUDSQRCsA) center;
width: 250px;
height: 100px;
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="multiselect">
<div class="select">Option1</div>
<div class="select">Option2</div>
<div class="select">Option3</div>
</div>
Instead of writing background-img url in javascrpt, I would suggest to create two classes having same properties but different background-img url which you want to toggle. so here we will be toggling class (ultimately background-img) in javascript.
see jsfiddle [example][1]
[1]: http://jsfiddle.net/09xgrhxo/13/

Applying CSS style to dynamically created DIV

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";
}

Categories