JS: how to switch CSS subclass of an object? - javascript

I want to change the view of an object from a JS function depending on any events.
For example, I have a set of forms, including an input form of type text. While it is not completely filled, the color of the frame and font is green, when it is completely filled - red.
At the same time, I want to keep the freedom of the HTML designer and give him the opportunity to set class names arbitrarily. I want to operate at the subclass level.
I set this:
.info.available {
color: green;
border: 1px solid lime;
}
.info.full {
color: red;
border: 1px solid red;
}
And
<input class="info available" type="text" id="info">
I have a function myfunc(obj) that takes a pointer "this" and works with different components of a formset.
How for obj.form.info ... to switch the subclass from "available" to "full" and vice versa? How can I get its current value?

first, specify an input maxlength to know if its is completely filled or not.
<input class="info available" max-length="10" type="text" id="input">
then remove the outline color from your input field when it is clicked or being typed
input.available {
border: 1px solid green;
}
input.full {
border: 1px solid red;
}
input:focus {
outline: none;
}
this is to make .available and .full classes visible. then add an action event to your input field that will listen for every string that is typed. you can do it by:
next in your script tag, create the function that will be fired from your input field
<script>
function myfunc(e) {
let x = document.getElementById('input')
if (x.value.length == 10)
{
x.classList.remove('available')
x.classList.add('full')
}
else {
x.classList.add('available')
x.classList.remove('full')
}
}
</script>
x refers to your input field
x.value.length refers to the length of characters that is in your input field
if x.value.length is equal to your input's maxlength(which we specified as 10), it will replace the class .available by .full and vice versa
you can read the documentation or tutorials here:
https://www.w3schools.com/js/js_events.asp
https://www.w3schools.com/tags/ref_eventattributes.asp

Use maxlength="{maxlen}" for your input.
function myfunc(obj) {
if (obj.value.length >= maxlen) {
obj.classList.remove('available');
obj.classList.add('full');
} else {
obj.classList.add('available');
obj.classList.remove('full');
}
}

Related

Can i put css on a condition required in javascript?

I want to know if there is a way to add css on a required element in JavaScript I have many condition and i want it just in this case i want something like that (I know i can't do this)
Thanks for your help !
if (!allAreFilled) { // While required element are empty
alert('Fill all the fields');
objForm.style:required.border = "solid 1px red"; // objForm = document.getElementById('compoundFormId')
}
With css:
input:required {
border: 1px dashed red;
}
You cannot directly change CSS style settings for pseudo elements or classes in Javascript.
But you can set CSS variables from JS.
This snippet sets a CSS variable --border when the submit button is clicked with the value depending on a condition.
const button = document.querySelector('button');
let conditionIsSet = true;
button.addEventListener('click', function() {
document.body.style.setProperty('--border', (conditionIsSet) ? 'red' : 'black');
});
body {
--border: black;
}
input:required {
border: var(--border) 1px solid;
}
<input type="checkbox" onchange="conditionIsSet = !conditionIsSet;">Select condition is true</input>
<br> Input without required: <input> Input with required: <input required>
<button>Submit</button>
Obviously you need to supply whatever condition is needed.

CSS Browser's text selection highlight color

Is it possible to get the browser's default (or themed, assuming there are browser themes? I've never looked) text selection color?
Background
I'm trying to make an <input type="date" /> act like it has a placeholder attribute, like the HTML5 <input type="text" /> does. In case it matters, I'm using Bootstrap.
So far, I've got
CSS
/* allow date inputs to have placeholders */
/* display placeholder text */
input[type="date"].emptyDate:before {
content: attr(placeholder);
color: #999;
}
/* hide default mm/dd/yyyy text when empty value and not in focus */
input[type=date].emptyDate:not(:focus) {
color: transparent;
}
/* hide default mm/dd/yyyy text when empty value, not in focus, and
selected (ctrl + a) */
input[type="date"].emptyDate::selection:not(:focus) {
color: transparent;
background-color: lightblue;
}
/* hide placeholder text when empty value, but in focus */
input[type="date"].emptyDate:focus:before {
content: "";
}
Javascript
function setEmptyDateInputClass(input) {
if ($(input).val()) {
$(input).removeClass("emptyDate");
} else {
$(input).addClass("emptyDate");
}
}
$(document).ready(function () {
$.each($("input[type=date]"), function (i, input) {
// set initial class
setEmptyDateInputClass(input);
// set class on value change
$(input).change(function () { setEmptyDateInputClass(this);});
});
});
Issues
I'm having two issues. The first, and the one I'm asking in this question (I'll post another question if everyone obeys the rules and no one posts answers to multiple questions) is, is there a way to get the browser's default (or themed) selection background color so that, either with CSS or manually with Javascript, the lightblue isn't static? (Also, light blue isn't the right color, but that's just a matter of a screenshot and mspaint.)
input[type="date"].emptyDate::selection:not(:focus) {
background-color: lightblue;
}
My second, bonus issue is, I'm having issues selecting :before::selection in order to set the background color of selected ::before content.
/* always active when .emptyDate */
input[type="date"].emptyDate::selection:before {
background-color: lightblue;
}
/* never active */
input[type="date"].emptyDate:before::selection {
background-color: lightblue;
}
You can use specificity on ::selection like so:
CSS
.red::selection {
background-color: red;
color: #fff;
}
.green::selection{
background-color:green;
color:#fff;
}
HTML
<span class="red">I am highlighted in red, </span>
<span class="green">and I am highlighted in green,</span>
<span class="">and I am highlighted as per browser default.</span>
Example: http://www.bootply.com/KEEvWSlP0F

Changing part of textbox input's color

I'm wondering if it's possible to change just a section of the a text input box's color. I am creating a comment widget want everything between the # and the : to change to a different color:
<input type="text" placeholder="Want To Say Something?"
value="#user556: This is a test comment" ng-model="Comment" ng-click="getCurrentPosition()"
class="form-control ng-valid valid ng-dirty">
Is this possible to do with jQuery or javascript? Or do I have to convert the text input to a div?
Possible, within a contenteditable element,
and with some JS and a bit of RegExp to replace the desired match:
function colorify() {
this.innerHTML = this.textContent.replace(/#([^:]+):/g, "#<span class='user'>$1</span>:");
}
function uncolorify() {
this.innerHTML = this.textContent;
}
[].forEach.call(document.querySelectorAll(".comment"), function(el){
el.addEventListener("blur", colorify);
el.addEventListener("focus", uncolorify);
});
[contenteditable] {
background:#fafafa;
padding:8px;
border-radius:3px;
border:1px solid #ddd;
}
[contentEditable]:empty:not(:focus):before {
/*http://stackoverflow.com/a/18368720/383904*/
content: attr(data-placeholder);
color: #777;
}
.user{
color: #f0f;
}
(Copy the following text into the contenteditable)<br>
#user547794: Use contenteditable. #johnDoe: nice suggestion btw.
<div class="comment" contenteditable data-placeholder="Want To Say Something?"></div>
Than click outside of the contenteditable.

css/javascript element returning false when it should return true

I have a one field form (text input and submit button). Here is the form code:
<form id="new_skill" class="new_skill" method="post" action="/skills" >
<li>
<input id="resume-field" class="field field288" type="text"
value="Type a speciality you want to add to your profile"
title="Type a speciality you want to add to your profile"
name="skill[label]"></input>
</li>
<li class="td80">
<input class="button button-add button-add-disabled"
type="submit" value="ADD +" name="commit"></input>
</li>
</form>
Using javascript, if text is entered in the text field, the submit button should be unclickable. If there is no text in the field, it should be clickable. I am doing that by using javascript to remove and/or put back the button-add-disabled class. Here is the javascript:
(function($){
$(document).on('focusin', '#resume-field', function() {
$(this).parents().find('.button-add-disabled').removeClass('button-add-disabled');
}).on('focusout', '#resume-field', function(){
if(this.value==' '||this.title==this.value) {
$(this).parents().find('.button-add').addClass('button-add-disabled');
} else {
$(this).parents().find('.button-add').removeClass('button-add-disabled');
}
});
$('.button-add-disabled').click(function(){
return false;
});
}(jQuery));
And here is the css:
.button-add { width: 49px; height: 28px; border: solid 1px #8c8c8c; display: block;
font-size: 11px; line-height: 28px ; color: #fff; text-align: center;
font-family: 'Ubuntu', sans-serif; transition: none; margin: 0 0 0 auto;
border-radius: 3px; }
.button-add:hover { text-decoration: none;
-webkit-transition:none;
-moz-transition:none;
-ms-transition:none;
-o-transition:none;
transition:none;
}
.td80 .button-add { margin-left:35px !important; }
.button-add-disabled { background: url(/assets/add-specialities-disabled.png)
repeat-x 0 0; box-shadow: 0 0 0 0; margin-left:35px; }
.button-add-disabled:hover { background: url(/assets/add-specialities-disabled.png)
repeat-x 0 0; box-shadow: 0 0 0 0; }
The classes are changing as expected and the javascript is working. For some reason though, even if .button-add-disabled is not applied to the form element, the form element is still returning false and therefore won't submit. When "button-add-disabled" is removed by the javascript, the form should submit. I can see the server logs. If I remove the line from the javascript "return: false", the form works, So i know the form itself works. I'm pretty sure something is wrong with the javascript. Any ideas?
That's not how that works. Events are bound to elements, which are reached via selectors; they are not bound to selectors.
When you bind the event directly to the element, the event is now bound to that element until you explicitly unbind it. The original selector is no longer relevant.
You need to do this, or something like it:
$('.button-add-disabled').click(function(){
return !$(this).hasClass('button-add-disabled');
});
That is, test whether the button is currently disabled by your class at the point the event is raised.
As an aside, this...
if(this.value==' '||this.title==this.value) {
$(this).parents().find('.button-add').addClass('button-add-disabled');
} else {
$(this).parents().find('.button-add').removeClass('button-add-disabled');
}
should be this:
var disabled = this.value == ' ' || this.title == this.value;
$(this).parents().find('.button-add').toggleClass('button-add-disabled', disabled);
You want to set/remove the disabled attribute of the input element, not set a CSS style which is for display purposes only
$('#resume-field').on('change', function() {
if ($(this).val().length == 0) {
$(this.form).find('input[type=submit]').attr('disabled', false).removeClass('button-add-disabled');
} else {
$(this.form).find('input[type=submit]').attr('disabled', true).addClass('button-add-disabled');
}
})
jsFiddle Demo
Also be sure that you handle the submission of the form when the user presses enter in the input field, you can do that using the jQuery .submit event handler and preventing the default behaviour. It is also essential you handle this server side.
EDIT: I just noticed what the CSS was doing, updated answer.

Change text input border color

I want to make a form where data is verified using JavaScript before being sent.
When a field is empty, I want to set its border to red.
HTML code:
<label>Question: </label><input type = "text" maxlength = "100" name = "question"> <br />
JavaScript code 1:
fields[i].style.borderColor = "red";
JavaScript code 2:
fields[i].style.border = "1px solid red";
If I use JS code 1, the border changes its color but it has the width bigger than before (even though I do not say anything about border width).
If I use JS code 2, the text input shrinks with 2px and the change is noticeable.
What should I do to change only the border color?
Actually this is preferred by adding and removing classes:
$("input").change(function()
{
var value = $(this).val();
if(value=="")
{
$(this).addClass("red-border");
$(this).focus();
}else
{
$(this).removeClass("red-border");
}
});
And your CSS:
.red-border{
border: 1px solid red;
}
The default user agent stylesheet uses this for the input field:
border: 2px inset;
Now you may ask why is this not defined by default?
by default(In IE the appreance is hard-coded):
appearance: textfield;
But whenever you change something:
appearance: none;
And when the appearance is none, you will see the 2px inset border.
So actually the width is the problem here:
So you want to change 2 propeties: Border-width and border-color
You would need 2 lines now:
document.getElementsByTagName('input')[0].style.border = "red";
document.getElementsByTagName('input')[0].style.borderWidth = "1px";
jsFiddle
However your own solution might be elegant, as it is defined with one line of code:
fields[i].style.border = "1px solid red";
Note that the inset style sets the top and right border lighter where the bottom and left border is the given color. Setting the style to solid will solve this.
It won't harm your code to use the whole shorthand property of border. You always have to be very specific when you want to win the battle with the user agent stylesheet.
I have something like this in production, only it uses alerts instead of color change. Use CSS Styles & classes:
CSS
.error {
border:2px solid red;
}
JavaScript
<script>
function checkField(){
var f = document.getElementById('<name of field>').value;
if (f === "") {
document.getElementById('<name of field>').className = document.getElementById('<name of field>').className + " error";
return false;
}
}
</script>
Then add this to your button/control's click event:
return checkField()
This SO post seems to be similar:changing textbox border colour using javascript
Use outline instead of border.
fields[i].style.outline = "1px solid red";
Try this out. Jquery
$("input").change(function ()
{
var value = this.value;
if(value=="")
{
$(this).css("border", "1px solid red");
}else
{
$(this).css("border",'');
}
}).trigger("change");
Html
<input type="text" class="col">

Categories

Resources