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'
}
});
Related
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.
I am truely sorry if this is a repeated question.
I want to set max-height of #menudd.show to satify my transition. I want to do this in javascript so i can specify the value more precisely.
This is what i got and its not working for some reason...
HTML:
<div id="menudd">
Home
About Me
Short-Term
Middle-Term
Long-Term
</div>
CSS:
#menudd {
position: fixed;
overflow: hidden;
max-height: 0px;
opacity: 0;
width: 200px;
border-radius: 10px;
box-shadow: 0 0 35px 15px black;
transition: all 1s ease;
}
#menudd.show {
opacity: 1;
}
JavaScript:
$("#menudd." + show).get(0).style.maxHeight = document.getElementById("menudd").getElementsByTagName("A")[0].offsetHeight * document.getElementById("menudd").getElementsByTagName("A").length + "px";
This outputs "show is not defined" in the console.
If i use $("#menudd.show").get(0).style.maxHeight it outputs "cannot read property 'style' of undefined" in the console.
If i use $("#menudd.show").style.maxHeight it outputs "cannot read property 'maxHeight' of undefined" in the console.
Any help is highly appreciated! Good day to you. :)
In your question, you said you wanted to look for an element with class "show" inside a div.
You are currently looking for a variable, and not a class. Change this:
$("#menudd." + show)
To this:
$("#menudd.show")
To set the max height, change it to this:
$( "#menuadd.show" ).css( { "maxHeight": document.getElementById("menudd").getElementsByTagName("A")[0].offsetHeight * document.getElementById("menudd").getElementsByTagName("A").length + "px" } );
First, I will add some stuff for readability - like a padding: 0.5em; into you dropdown menu. Also, the <br /> tag after the </a> tags (excluding the last one).
Second, the errors happened because there are no element in the page with the class show. I added it to the <div> of the dropdown to show it working and make the errors go away.
Remember this: if the console says there it is undefined, chances are that either you messed up in how to select the element OR it seriously doesn't exists because you misspelled a letter or let's say you forgot to add a class to a given tag (like in this case).
Third, your code in working condition is available below. It isn't using jQuery easing stuff but pure JavaScript - except by the onclick event that is better to use with jQuery:
$("#menu-dropdown").on("click", function() {
var menu_dropdown = document.getElementById("menudd");
var menu_item = menu_dropdown.getElementsByTagName("A");
$("#menudd").toggleClass("show");
menu_dropdown.style.maxHeight = menu_item[0].offsetHeight * menu_item.length + "px";
} );
#menudd {
padding: 0.5em;
position: fixed;
overflow: hidden;
max-height: 0px;
opacity: 0;
width: 200px;
border-radius: 10px;
box-shadow: 0 0 35px 15px black;
transition: all 1s ease;
}
#menudd.show {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<span id="menu-dropdown">DropDown</span>
<div id="menudd">
Home<br />
About Me<br />
Short-Term<br />
Middle-Term<br />
Long-Term<br />
</div>
You can view it working also on this video (Youtube) that I recorded.
Fourth, you can add classes, in pure JavaScript, easily. I won't write about it in full since there is a famous question with a godly answer by Peter Boughton already on Stack Overflow. Read it here.
Anyway, to add a class, simply call:
document.getElementById("MyElementID").className += " MyClass";
It is important to note the space. Since it is a string with values, you need to put it otherwise it will treat all the classes as one word (one class) that doesn't exists.
To remove:
document.getElementById("MyElementID").className = document.getElementById("MyElementID").className.replace( /(?:^|\s)MyClass(?!\S)/g , '' );
Explanation available through Peter's answer. So read it there (important)!
Finally, this is out of the scope of the question and merely a reminder: I need to state that if this is a dropdown menu, you will need to add the show class after some focus (or click even) by calling a function in a master menu of some sort and not by hardcoding it into the <div> like I did to show the code working. For example, a "Cars Brand" item of a menu would have a dropdown with the available car brands (Ford, Toyota and etc) after focusing on it.
So, it is wise to transform it in a function that receives the ID of the target dropdown to open. And do not forget to close it after losing focus (or whatever).
I am trying to create a Lightbox-like effect with CSS and Javascript. I'm getting an element by it's id (OverlayContainer) and it will change it's classname to accomodate the dark background for now. I have set up the code in a way that it checks classname value of the element (OverlayContainer) to see whether the classname is set to inactive(normal background) or active (darker). However when i press the submit button to change the state it appears to change classes for a second (screen gets darker for a split second) but then reverts back to original state (OverlayInactive). If anyone has any kind of explanation for this happening please respond.
Here is my CSS code:
.OverlayBoxInactive {
background-color: rgba(0, 0, 0, 0);
position: absolute;
width: 0%;
height: 0%;
top: 0px;
left: 0px;
}
.OverlayBoxActive {
background-color: rgba(0, 0, 0, 0.85);
position: absolute;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
}
and here is my Javascript code:
function ActivateOverlay() {
var overlayBox = document.getElementById("OverlayContainer");
var elementClassName = overlayBox.className;
if (elementClassName == "OverlayBoxInactive") {
overlayBox.setAttribute("class", "OverlayBoxActive");
//alert('Overlay Activated');
} else if (elementClassName == "OverlayBoxActive") {
overlayBox.setAttribute("class", "OverlayBoxInactive");
//alert('Overlay Inactivated');
}
}
Thanks in advance,
-Realitiez
EDIT POST: http://jsfiddle.net/bk5e9t0e/
The default action of an input type="submit" is to post the form's data back to the server, which causes your page to reload. This is why your class is removed.
If you wish to prevent the page reload, you need to prevent the default action. The easiest way to do this is to return false from the onclick handler:
onclick="ActivateOverlay(); return false;"
Your code was not working because:
You were using input type=submit [so you were getting a refresh page kind of feel], which should be type=button or return false; in click handler
You were calling function ActivateOverlay which was defined later than the call itself.
Find your solution here in jsFiddle
<script>
function ActivateOverlay() {
//alert('Overlay Activated');
var overlayBox = document.getElementById("OverlayContainer");
var elementClassName = overlayBox.className;
if (elementClassName == "OverlayBoxInactive") {
overlayBox.setAttribute("class", "OverlayBoxActive");
//alert('Overlay Activated');
} else if (elementClassName == "OverlayBoxActive") {
overlayBox.setAttribute("class", "OverlayBoxInactive");
//alert('Overlay Inactivated');
}
}
</script>
<div id="OverlayContainer" class="OverlayBoxInactive"></div>
<div class="main"></div>
<fieldset>
<form>
<input type="button" onclick="ActivateOverlay();return false" value="Hit Me"></input>
</form>
</fieldset>
<script type="text/javascript" src="index.js"></script>
http://jsfiddle.net/4queag8m/
You need to add an preventDefault() in your function. it's reloading the page.
First add the element to your call:
onclick="ActivateOverlay(this)"
and then add the parameter with the prevent to your function - like this"
function ActivateOverlay(evt) {
evt.preventDefault()
...
}
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");
N.B.: I should note that the proper solution to this is to just use the 'placeholder' attribute of an input, but the question still stands.
Another N.B.: Since, as Quentin explains below, the "value" attribute stores the default value, and the input.value IDL attribute stores the current value, the JavaScript I used to "fix" the problem in my below example is non-conforming, as it uses the (non-IDL) value attribute to store current, rather than default, values. Besides, it involves DOM access on every key press, so it was always just a flawed demo of the problem I was having. It's actually quite terrible code and shouldn't be used ever.
CSS selectors made me think that I could make an input with a label that acts as a preview without any JS. I absolutely position the input at 0,0 inside the label (which is displayed as an inline-block) and give it a background of "none", but only if it's got a value of "" and isn't focussed, otherwise it has a background colour, which obscures the label text.
The HTML5 spec says that input.value reflects the current value of an input, but even though input.value updates as you type into an input, CSS using the input[value=somestring] selector applies based only on what was explicitly typed into the document, or set in the DOM by the JavaScript setAttribute method (and perhaps by other DOM-altering means).
I made a jsFiddle representing this.
Just in case that is down, here is an HTML document containing the relevant code:
<!doctype html>
<head>
<meta charset="utf-8" />
<title>The CSS Attribute selector behaves all funny</title>
<style>
label {
display: inline-block;
height: 25px;
line-height: 25px;
position: relative;
text-indent: 5px;
min-width: 120px;
}
label input[value=""] {
background: none;
}
label input, label input:focus {
background: #fff;
border: 1px solid #666;
height: 23px;
left: 0px;
padding: 0px;
position: absolute;
text-indent: 5px;
width: 100%;
}
</style>
</head>
<body>
<form method="post">
<p><label>name <input required value=""></label></p>
</form>
<p><button id="js-fixThis">JS PLEASE MAKE IT BETTER</button></p>
<script>
var inputs = document.getElementsByTagName('input');
var jsFixOn = false;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].parentNode.tagName == 'LABEL') { //only inputs inside a label counts as preview inputs according to my CSS
var input = inputs[i];
inputs[i].onkeyup= function () {
if (jsFixOn) input.setAttribute('value', input.value);
};
}
}
document.getElementById('js-fixThis').onclick = function () {
if (jsFixOn) {
this.innerHTML = 'JS PLEASE MAKE IT BETTER';
jsFixOn = false;
} else {
this.innerHTML = 'No, actually, break it again for a moment.';
jsFixOn = true;
}
};
</script>
</body>
</html>
I could be missing something, but I don't know what.
The value attribute sets the default value for the field.
The value property sets the current value for the field. Typing in the field also sets the current value.
Updating the current value does not change the value attribute.
Attribute selectors only match on attribute values.
There are new pseudo classes for matching a number of properties of an input element
:valid
:invalid
:in-range
:out-of-range
:required
A required element with no value set to it will match against :invalid. If you insist on using the value instead of placeholder, you could simply add a pattern or a customValidity function to force your initial value to be counted as invalid.