Archivi tag: html

SetStyle: Set CSS Properties Without Surprises

Ultimo aggiornamento: 31-01-2014

Introduction

Using JavaScript to make HTML element, often is used elem.setAttribute("style", "property1:val; property2:val;") to set CSS properties in easy way; but there’s a problem if you had just set a CSS property with elem.style.prop="val" : it will be reset to default browser value!! (Run the test code showed below.)

So I made a simple function to solve this problem and continue to use a setAttribute-like approach.

Using the Code

I wrote the setStyle method in HTMLElement interface, that represents any HTML element, so to use it easily.

This is the function:

HTMLElement.prototype.setStyle = function(str) {    
    var props = str.split(";"); //get properties
    for(var i = 0; i < props.length; i++) {
        var t = props[i].split(":"); //t[0] = property - t[1] = value
        this.style[fixPropName(t[0].trim())] = t[1].trim(); //trim removes white space(s)
    }
}

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

//trasform text, for example, from background-color to backgroundColor
function fixPropName(str) {
    var tArray = str.split("-");
    var prop = tArray[0];
    for(var i = 1; i < tArray.length; i++) {
        prop += tArray[i].capitalize();
    }
    return prop
}

Now you can use this function, in this way:

var div = document.getElementById("IdElement");
div.setStyle("background:blue; color: white");

This function is just a millisecond (on my PC, and sometimes) slower than setAttribute method, but now you are sure to haven’t unexpected CSS properties change.

To make a test, run this code:

<script>
HTMLElement.prototype.setStyle = function(str) {    
    var props = str.split(";"); //get properties
    for(var i = 0; i < props.length; i++) {
        var t = props[i].split(":"); //t[0] = property - t[1] = value
        this.style[fixPropName(t[0].trim())] = t[1].trim(); //trim removes white space(s)
    }
}

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

//trasform text, for example, from background-color to backgroundColor
function fixPropName(str) {
    var tArray = str.split("-");
    var prop = tArray[0];
    for(var i = 1; i < tArray.length; i++) {
        prop += tArray[i].capitalize();
    }
    return prop
}
window.addEventListener("DOMContentLoaded", 
function(e) {

var div = document.getElementById("cc");
div.style.opacity = "1";
str = "Opacity: " + div.style.opacity + "<br />";
var endTime, startTime = Date.now(); 
div.setAttribute("style","background:green;color:black");
endTime = Date.now(); 
str += "TimeExec: " +(startTime-endTime) + "<br />";
str += "Opacity: " + div.style.opacity + "<br /><br />";

div.style.opacity = "1";
str += "Opacity: " + div.style.opacity + "<br />";
startTime = Date.now(); 
div.setStyle("background:blue; color: white");
endTime = Date.now(); 
str += "TimeExec: " +(endTime-startTime) + "<br />";
str += "Opacity: " + div.style.opacity + "<br />";

div.innerHTML = str;
}, false);
</script>

<div id="cc">To to to</div>

Article on CodeProject

HTML5 Form Validation and Alternative Inputs

Ultimo aggiornamento: 16-03-2017

I have written a new tip on HTML5 form validation (original article is on codeproject.com)

Introduction

Often in a form, there’s the need to insert only an input or two, and make checks on them. Here, I’ll show how to do this with HTML5 form validation, without JQuery or others frameworks.

Background

To understand this trick, you should know how HTML5 form validation works and a bit of JavaScript. Continue reading HTML5 Form Validation and Alternative Inputs

Customize HTML5 form validation with JavaScript and CSS

Ultimo aggiornamento: 11-05-2013

Introduction

With HTML5, to check forms validity, new input type values (email, URL, etc.) and also the pattern attribute were introduced, but the control is done when the form is submitted.

Is there a way to do this before that?

JavaScript

There are many ways to personalize control validation, not only the message of error with setCustomValidity or the use of title and x-moz-errormessage into input tag, but also calling the checkValidity() function to check inputs values on some input event as onchange.

Here the JavaScript code of example:

window.onload=function() {
    var query = ["input[pattern]", "input[type=email]"];
    for(var q = 0; q < query.length; q++) {
        var inp = document.querySelectorAll(query[q]);
        for(var i = 0; i < inp.length; i++) {
                inp[i].onkeyup = validation;
        }
    }
};

function validation(event) {
    var p = this.parentNode.querySelector("p");
    if (this.checkValidity() == false) { //the control is here!
        p.innerHTML=this.getAttribute("title");
    } else {
        p.innerHTML="";
    }     
}

And this is the HTML code:

<form>
  <fieldset>
    <legend>Form</legend>
    <div>
      <label for="input01">Name</label>
          <div>
            <input type="text" pattern="[a-zA-Z ]+" 
              required title="Insert only letters of the alphabet" id="input01" name="name" >
            <p class="err-msg"></p>
          </div>
      </div>
       <div>
          <label for="input02">Pin</label>
          <div >
            <input type="text" pattern="[a-zA-z0-9]{16}"  
              required  title="Insert 16 chars" maxlength="16" id="input02"  name="pin"> 
            <p  class="err-msg"></p>
          </div>
      </div>
       <div>     
           <label for="input03">Cellphone</label>
          <div>
            <input type="text"  pattern="[0-9]+" 
              required  title="Insert only numbers chars" id="input03" name="cell" >
            <p class="err-msg"></p>
           </div>
      </div>
      <div>     
          <label for="input04">Email</label>
          <div >
              <input type="email" required title="Insert a valid email" id="input04" name="email">
            <p class="err-msg"></p>
          </div>
      </div>

     <div style="width:100%; text-align:center;">
       <input type="submit">
       <input type="reset" >  
     </div>
  </fieldset>
</form>

Take a look:

  • The title attribute value is used by browsers to personalize the error message for an input.
  • The required attribute  specifies that an input field must be filled out before submitting the form.

CSS

You can personalize also the inputs style with pseudo-classes: :invalid, :valid, :required.

Other pseudo-classes can be found here: CSS Basic User Interface Module Level 3 (CSS3 UI)

For example, with the following CSS rule, input texts will be red until the input is invalid.

input:invalid {
    color:red;
}