How do you set a css class attribute with Javascript? [duplicate] - javascript

This question already has answers here:
How to add a class to a given element?
(28 answers)
Closed 7 years ago.
The element i'm working with is a image i would like displayed during load time.
I am trying to set a css class attribute, i can set attributes on my image but its class attributes override's it.
So i need to set the class attribute. The class is .bgImage
This is how i set the attribute:
LoadingImg.setAttribute("display", "block");
This is what i have tried:
LoadingImg.className("display", "block");
And
LoadingImg.setAttribute(".bgImage display", "block");
CSS:
.bgImage {
position: fixed;
top: 0; left: 33%;
right: 0; bottom: 0;
z-index: 1;
display: none;
background-repeat:no-repeat;
}
Exstra info:
LoadingImg is the image object, i had to grab it through iFrame levels.
var HomeDoc = $('#ContentFrame').contents()[0];
var LoadingImg = HomeDoc.all.namedItem('LoadingImg');

Use the style property to set the style in javascript.
LoadingImg.style.display = "block";

If you want to use jQuery you can try:
$( "#LoadingImg" ).css( "display","block" );

You may use jQuery LoadingImg.addClass( ".bgImage" ).css("display", "block");
or
LoadingImg.attr("class", ".bgImage").css("display", "block");

Related

How to change CSS float value through javascript [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 3 years ago.
I'm using div with CSS value float: right;. I would like to change that by using JavaScript to change float attribute to left using on click function.
So I'm using click event listener:
document.getElementById("english").addEventListener("click", function isEnglish(){
document.getElementsByClassName('tab').style.cssFloat = "left";
});
but I fail to change float direction, the element stays in the same place. Codepen
How can I change float direction using JavaScript?
document.getElementsByClassName('tab') returns a list of elements to you may have to iterate over it.
The js property for float is float instead of ccsFloat you used in your code.
document.getElementById("english").addEventListener("click", function isEnglish(){
Array.from(document.getElementsByClassName('tab')).forEach(v => {
v.style.float = "left";
});
});
p {
width: 50px;
height: 50px;
float: right;
margin: 10px;
background: red
}
<p class="tab">a</p>
<p class="tab">b</p>
<p class="tab">c</p>
<p class="tab">d</p>
<p class="tab">e</p>
<button id="english">english</button>

How do you remove CSS style inside a style element?

Example:
<style>
.className {
left: 0;
color: blue;
}
</style>
I want to remove the left: 0; aspect using javascript/jquery or whatever method I have to use to do this. I don't have the option of opening the document to edit or delete. Any Ideas? Note that this class has other styles within it and I just want to remove the left:0; aspect ONLY leaving the rest intact.
An element's style attribute can override its CSS class properties. left: auto will also reset the left property of an element to the default value.
An element's style can be set like this in Javascript:
Element.style.[CSS property] = [value]
<span id="someId">Span</span>
<script>
document.getElementById("someId").style.color = "#aeb";
</script>
Its jQuery equivalent is (for one CSS property):
$([selector]).css([CSS property], [value]);
$('#someId').css("color", "#aeb");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="someId">Span</span>
For many CSS properties:
$([selector]).css({[CSS property]: [value], [CSS property]: [value]});
$('#someId').css({"color":"red", "font-size":"1.5em", "position":"absolute", "top": "25%", "left": "25%"});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="someId">Span</span>
<style>
.className {
left: 0;
position: absolute;
}
</style>
<span class="className">Span.className</span><br/>
<span class="className">Span.className</span><br/>
<span class="className">Span.className</span><br/>
<span class="className">Span.className</span><br/>
<span class="className">Span.className</span><br/>
<span style="left: 0; position: absolute;">Span with left:0 and position:absolute</span>
<script>
var elems = document.getElementsByClassName("className");
for(let i = 0; i < elems.length; i++){
elems[i].style.left = "50px";
}
</script>
To overwrite all previous set CSS properties of an element, you can use all: initial, setting all CSS properties to its initial value.
<style>
.someClass{
position: fixed;
color: red;
background-color: dodgerblue;
font-size: 3em;
margin: 20px;
}
</style>
<span class="someClass">Span.someClass</span>
<span class="someClass" style="all: initial;">Span.someClass all:initial</span>
left:auto;
Auto will reset the left attribute to the browser's default for the page :)
possible / similar duplicate:
How to remove Left property when position: absolute?
Using jquery you should be able to simply do this:
$('.className').css({'left': 'auto'});
Or, if the class isn't really all that important anyways, you could just remove it like this:
$('.className').removeClass('className');
You could override it with another value either in CSS, or using the same jQuery thing mentioned in the first part of my answer.
Here are two different approaches.
1. Replace/Remove the class
If that is the only style attribute in that class, you could remove the class from all elements that use it.
Example with jQuery:
$(".className").removeClass("className").addClass("anotherClass");
2. Override the attribute
The default value for left in CSS is auto, so you could override the CSS for all of those elements.
Example with jQuery:
$(".className").css("left", "auto");
Try like this:
$('.className').remove();
Since it has a value, making the value blank will make it so it doesn't count as any value and the css attribute will be skipped/ignored.
Solution:
$('.className').css('left',' ');
If the attribute still gets read as 0 then you will have to apply the !important to the .css(); to override it.

jQuery .css() method not working

I have a code that uses jQuery .css() method to modify the style of a DIV but it is not working. Here is a simplified version of my code that replicates the issue.
HTML:
<input type="radio" name="show" id="showleft" value="showleft">Left
<input type="radio" name="show" id="showright" value="showright">Right
<div id="cfwrapper">XXXXXXXXX</div>
CSS:
#cfwrapper {
bottom: 10px;
left: 30px;
position: fixed;
}
JavaScript:
$("input:radio[name=show]").click(function(event){
if (event.target.id == 'showleft') {
// remove property 'right:30px'
// add property 'left:30px'
} else if (event.target.id == 'showright') {
$('#cfwrapper').css('left',''); // remove property 'left:30px'
// add property 'right:30px'
}
});
What happens in the above code is that the line $('#cfwrapper').css('left',''); does not work. I would expect it to remove the 'left' property from "cfwrapper" ("XXXXXXXXX" would then move 30px to the left) and then I would use a similar statement - $('#cfwrapper').css('right','30px'); - to add a "right" property so that "XXXXXXXXX" would then go to the right of the page, but it does not work.
Can anyone tell me why it is not working? Wasn't it supposed to work?
JSFiddle: http://jsfiddle.net/fidnut/hLqngbsb/
try this .css('left','auto')
$("input:radio[name=show]").click(function(event){
if (event.target.id == 'showleft') {
document.getElementById('op').innerHTML='Left side';
$('#cfwrapper').css({'left':'30px','right':'auto'});
} else if (event.target.id == 'showright') {
document.getElementById('op').innerHTML='Right side';
$('#cfwrapper').css({'left':'auto','right':'30px'});
}
});
http://jsfiddle.net/hLqngbsb/2/
Please see the answer to this question.
From the jQuery docs:
Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.
A more maintainable approach would be to add/remove classes to control the styling:
http://jsfiddle.net/0hh80mkd/2/
Use class
.cfwrapper {
bottom: 10px;
left: 30px;
position: fixed;
}
.cfwrapperDis{
bottom: 10px;
left: 30px;
position: fixed;
}
then
$("input:radio[name=show]").click(function(event){
if (event.target.id == 'showleft') {
// remove property 'right:30px'
// add property 'left:30px'
} else if (event.target.id == 'showright') {
$('#cfwrapper').removeClass("cfwrapper").addClass("cfwrapperDis"); // remove property 'left:30px'
// add property 'right:30px'
}
});

Change CSS Property through JavaScript. (Uses ID's and Classes)

I'm trying to resize a panel using JavaScript to fit a small image into a panel, and struggling badly.
It's within the bold:
<body id="visCinemaTransRefund"><br>
<div id="content"><br>
<ul class="PayPanel" id="paymentDetails"><br>
Here's the CSS that needs modifying:
visCinemaTransRefund .PayPanel { width: 435px; }
How would I be able to modify with width of this panel?
I've also got a form I'm trying to resize within CSS:
visCinemaTransRefund FORM (width: 1005px;)
document.getElementById('paymentDetails').style.width = '1000px';
Have you tried using:
document.getElementById("paymentDetails").getElementsByClassName("PayPanel")[0].style.width="1000px"
Remember: getElementsByClassName return an array of elements, so using [0] you are indexing first element (and, of course, the only one).
Since getElementsById return a single elements, getElementsByClassName could be useless.
If you want to do this using CSS class :
HTML:
<div id="myDiv" class="medium"></div>
<button id="btn">Click me</button>
CSS:
#myDiv {
background-color: gray;
}
.medium {
height: 50px;
width: 50px;
}
.big {
height: 100px;
width: 100px;
}
JS:
document.getElementById("btn").onclick = function() {
var element = document.getElementById("myDiv"); // or document.getElementsByClassName("className")
if (element.className == "medium") {
document.getElementById("myDiv").className = "big";
} else {
document.getElementById("myDiv").className = "medium";
}
};
JSFIDDLE
Use the following code to change the width of tags by accessing HTML element from the DOM using getElement functions and setting width to it using setAttribute javaScript function.
document.getElementById("paymentDetails").setAttribute("style","width:500px;");
document.getElementById("visCinemaTransRefund").getElementsByTagName("form")[0].setAttribute("style","width:1000px;");
Using JavaScript:
document.getElementById('paymentDetails').style.width = '1000px';
Using JQuery:
$("paymentDetails").width(1000);
$("paymentDetails").css("width","1000px");

How change content value of pseudo :before element by 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)
Closed 2 years ago.
I have the grap constructured by CSS, which is dynamically changes by JS. I show graph max value by pseudo element as:
.graph:before {
content:""; //value that want set by JS
position:absolute;
top:0;
left:0;
}
That's why I need to set this value by JS. I tried $(".graph:before").css("content", hh); but it didn't help. How to get that value?
I hope the below snippet might help, you can specify the content value you want via JS using the CSS attr() function.
Below you have two options: to use JavaScript or jQuery:
jQuery:
$('.graph').on('click', function () {
//do something with the callback
$(this).attr('data-before','anything'); //anything is the 'content' value
});
JavaScript:
var graphElem = document.querySelector('.graph');
graphElem.addEventListener('click', function (event) {
event.target.setAttribute('data-before', 'anything');
});
CSS:
.graph:before {
content: attr(data-before); /* value that that refers to CSS 'content' */
position:absolute;
top: 0;
left: 0;
}
Update (2018): as has been noted in the comments, you now can do this.
You can't modify pseudo elements through JavaScript since they are not part of the DOM. Your best bet is to define another class in your CSS with the styles you require and then add that to the element. Since that doesn't seem to be possible from your question, perhaps you need to look at using a real DOM element instead of a pseudo one.
You can use CSS variable
:root {
--h: 100px;
}
.elem:after {
top: var(--h);
}
let y = 10;
document.documentElement.style.setProperty('--h', y + 'px')
https://codepen.io/Gorbulin/pen/odVQVL
I believe there is a simple solution using the attr() function to specify the content of the pseudo element. Here is a working example using the 'title' attribute, but it should work also with custom attributes.:
document.getElementById('btn_change1').addEventListener("click", function(){
document.getElementById('test_div').title='Status 1';
});
document.getElementById('btn_change2').addEventListener("click", function(){
document.getElementById('test_div').title='Status 2';
});
#test_div {
margin: 4em;
padding:2em;
background: blue;
color: yellow;
}
#test_div:after {
content:attr(title);
background: red;
padding:1em;
}
<button id='btn_change1'>Change div:after to [Status 1]</button>
<button id='btn_change2'>Change div:after to [Status 2]</button>
<div id='test_div' title='Initial Status'>The element to modify</div>
People who are still looking some solution of same problem, it is doable as follows using jQuery:
<button id="changeBefore">Change</button>
<script>
var newValue = '22';//coming from somewhere
var add = '<style>.graph:before{content:"'+newValue+'"!important;}</style>';
$('#changeBefore').click(function(){
$('body').append(add);
});
</script>
This example illustrate that on clicking button: changeBefore , the value for .graph:before will change as per new dynamic coming value for it.
For more description about changing of :before or :after element style or getting its content:
Lets suppose your HTML is like this:
<div id="something">Test</div>
And then you are setting its :before in CSS and designing it like:
#something:before{
content:"1st";
font-size:20px;
color:red;
}
#something{
content:'1st';
}
Please notice I also set content attribute in element itself so that you can take it out easily later.
Now there is a button clicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:
Define a css with your required style on some class .activeS :
.activeS:before{
color:green !important;
font-size:30px !important;
}
Now you can change :before style by adding the class to your :before element as follows:
<button id="changeBefore">Change</button>
<script>
$('#changeBefore').click(function(){
$('#something').addClass('activeS');
});
</script>
If you just want to get content of :before, it can be done as:
<button id="getContent">Get Content</button>
<script>
$('#getContent').click(function(){
console.log($('#something').css('content'));//will print '1st'
});
</script>
I hope it helps
I had a similar problem, but with icons. I needed to switch the play and pause icons for an audio player in html5.
The problem here was that HTML, CSS and jQuery all interpret differently the "content" values to show icons, due to the use of \ symbol.
So the best workaround is to delete and re-create the node. Here's my code:
<ul class="list list--buttons">
<li><i class="fa fa-step-backward"></i></li>
<li><i class="fa fa-play"></i></li>
<li><i class="fa fa-step-forward"></i></li>
</ul>
And the script
<script type="text/javascript">
$(
function(){
var aud = $('audio')[0];
$('.playpause').on('click', function(e){
e.preventDefault();
if (aud.paused) {
aud.play();
/* from play icon to pause icon */
$('.playpause .fa-play').remove();
$('.playpause').append('<i class="fa fa-pause"></i>');
}
else {
aud.pause();
/* from play icon to pause icon */
$('.playpause .fa-pause').remove();
$('.playpause').append('<i class="fa fa-play"></i>');
}
})
$('.next').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
$('.previuos').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
aud.ontimeupdate = function(){
$('.progress').css('width', aud.currentTime / aud.duration * 100 + '%')
}
})
</script>
Hope it helps!
You can use document.styleSheets to modify pseudo selector cssRules
document.styleSheets[0].cssRules[0].style.content = '"111"';
If you use something like an onoffswitch and want to translate the css content attribute with i18next then you can use one of the i18next Framework example from github (i18next Jquery Framework) and then you extended the function with this code:
var before = i18next.t('onoffswitch.before');
var after = i18next.t('onoffswitch.after');
$('.onoffswitch-inner')
.attr('data-before', before )
.attr('data-after', after );
and the css code must be this:
.onoffswitch-inner:before {
content: attr(data-before);
padding-left: 10px;
background-color: #65AFF5; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: attr(data-after);
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}

Categories

Resources