What is the alternative of placeholder in html for xhtml? - html

What is the XHTML equivalent of HTML placeholder.

placeholder is new in HTML 5.
There is no equivalent in XHTML 1.x (which is the XML version of HTML 4.x)
It is, of course, available in the XML serialisation of HTML 5.
Failing that, you would have to fake it using JavaScript (which is probably best done by absolutely positioning a second <label> element under the <input> which you set to have a transparent background colour unless it has a value or the focus).

I did a experiment to simulate the placeholder using xhtml+js+css as happen on HTML5 placeholder property.
xhtml:
<input id="textbox-obj" type="text" class="search-txt" data-placeholder="Search" title="Search something here">
Javascript (jquery):
//Function to place the textbox cursor to the begining
function moveCursorToStart(el) {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = 0;
} else if (typeof el.createTextRange != "undefined") {
el.focus();
var range = el.createTextRange();
range.collapse(true);
range.select();
}
}
function initSearchTextPlaceholder(textBox) {
textBox.focus(function() {
if( $(this).val() == $(this).attr('data-placeholder') ) {
moveCursorToStart(this);
// To fix Chrome's bug
window.setTimeout(function() {
moveCursorToStart(this);
}, 1);
}
}).blur(function() {
if( $(this).val() == $(this).attr('data-placeholder') || $(this).val() == '' ) {
$(this).addClass('placeholder').val($(this).attr('data-placeholder'));
}
}).on('keypress', function() {
if( $(this).val() == $(this).attr('data-placeholder') ) {
$(this).removeClass('placeholder').val('');
}
}
).blur();
}
initSearchTextPlaceholder($("#textbox-obj"));
CSS
.search-txt {
color: #333;
}
.search-txt.placeholder {
color: #8d8d8d;
}

Related

Adjust the width of an element based on the width of another element

Please check the solution here:
https://stackoverflow.com/a/41686102/4180447
The above solution can be used to implement editable dropdown (select) element in Angular. However, the width of the element is assumed to be fixed. Now, we are implementing responsive design, and I need a way to adjust the width of an element based on the width of another element.
Basically, the implementation uses two elements and places them on top of each other. One element is the select element whose ID ends with _sel , and the other is the text element whose ID ends with _disp. The text element must be narrower than the drop-down element so that the drop-down arrow will be visible.
The width of the text element must be about 18px less than the width of the select element.
Is there a way to adjust the height of the text input the be 18px less than the size of the select element?
See snapshot below and related code to clarify the situation:
HTML:
<div class="select-editable stop-wrap" style="width: 265px; border:none">
<select type="text" id="exterior_finish_sel" editable-dropdown="exterior_finish" name="exterior_finish_sel"
ng-model="exterior_finish_sel" ng-options="o as o for o in ddlOptions.exterior_finish track by o" maxlength="80"
class="ng-valid ng-valid-maxlength ng-not-empty ng-dirty ng-valid-parse ng-touched" style="">
</select>
<input type="text" id="exterior_finish_disp" name="exterior_finish_disp" ng-model="exterior_finish_disp" style="width: 247px;"/>
<input type="text" id="exterior_finish" name="exterior_finish" ng-model="exterior_finish" ng-hide="true"/>
</div>
CSS:
.stop-wrap {
display: inline-block;
}
.select-editable {
position:relative;
background-color:white;
border:solid grey 1px;
width:120px;
height:25px;
vertical-align: middle;
margin-bottom: 5px;
}
.select-editable select {
position:absolute;
top:0px;
left:0px;
border:none;
width:118px;
margin:0;
}
.select-editable input {
position:absolute;
top:0px;
left:0px;
width:100px;
padding:1px;
border:none;
}
.select-editable select:focus, .select-editable input:focus {
outline:none;
}
I found the answer based on solution here:
https://stackoverflow.com/a/18743145/4180447
The jQuery plugin that will monitor changes on width/position:
jQuery.fn.onPositionChanged = function (trigger, millis) {
if (millis == null) millis = 100;
var o = $(this[0]); // our jquery object
if (o.length < 1) return o;
var lastPos = null;
var lastOff = null;
var lastWidth = null;
var lastOffWidth = null;
setInterval(function () {
if (o == null || o.length < 1) return o; // abort if element is non existend eny more
if (lastPos == null) lastPos = o.position();
if (lastOff == null) lastOff = o.offset();
if (lastWidth == null) lastWidth = o.width();
if (lastOffWidth == null) lastOffWidth = o[0].offsetWidth;
var newPos = o.position();
var newOff = o.offset();
var newWidth = o.width();
var newOffWidth = o[0].offsetWidth;
if (lastPos.top != newPos.top || lastPos.left != newPos.left) {
$(this).trigger('onPositionChanged', { lastPos: lastPos, newPos: newPos });
if (typeof (trigger) == "function") trigger(lastPos, newPos);
lastPos = o.position();
}
if (lastOff.top != newOff.top || lastOff.left != newOff.left) {
$(this).trigger('onPositionChanged', { lastOff: lastOff, newOff: newOff});
if (typeof (trigger) == "function") trigger(lastOff, newOff);
lastOff= o.offset();
}
if (lastWidth != newWidth) {
$(this).trigger('onPositionChanged', { lastWidth: lastWidth, newWidth: newWidth});
if (typeof (trigger) == "function") trigger(lastWidth, newWidth);
lastWidth= o.width();
}
if (lastOffWidth != newOffWidth) {
$(this).trigger('onPositionChanged', { lastOffWidth: lastOffWidth, newOffWidth: newOffWidth});
if (typeof (trigger) == "function") trigger(lastOffWidth, newOffWidth);
lastWidth= o.width();
}
}, millis);
return o;
};
The editable-dropdown directive below:
app.directive('editableDropdown', function ($timeout){
return {
link: function (scope, elemSel, attrs) {
//This is the hidden input, and will be used for data binding
var inpElemID = attrs.editableDropdown;
var inpElem;
//This is the display element and will be used for showing the selected value
var inpElemDispID = inpElemID + "_disp";
var inpElemDisp;
//The parameter 'elemSel' is the SELECT field
function initInpElem() {
//Get a reference to the hidden and displayed text field
if ($(elemSel).is("select")) {
inpElem = $('#' + inpElemID); //Hidden field
inpElemDisp = $('#' + inpElemDispID); //Displayed field
} else {
//This is in case the Dropdown is based on DATALIST which is not yet implemented
//In this case, the input element is actually the same as the dropdown field using DATALIST
inpElem = elemSel;
}
}
initInpElem();
function updateEditable(elm) {
initInpElem();
//Copy value from SELECT element to the INPUT Element
//Use NgModelController to copy value in order to trigger validation for 'inpElem'
var selectedValue = $(elm).children("option").filter(":selected").text();
//Update the hidden text field which is used to save the value to DB
angular.element(inpElem).controller('ngModel').$setViewValue(elm.val());
angular.element(inpElem).controller('ngModel').$render();
//Update the display text field based on the selection (text value)
angular.element(inpElemDisp).controller('ngModel').$setViewValue($(elm).find('option:selected').text());
angular.element(inpElemDisp).controller('ngModel').$render();
makeEditable(elm);
}
function makeEditable(selElm) {
//Allow edit text field if "other" is selected
initInpElem();
if ($(selElm).is("select")) {
//JIRA: NE-2995 - of option seletec starte with "other" then activate editable option
if (selElm.val().toLowerCase().startsWith("other")) {
//Make the display field editable
$(inpElemDisp).prop("readonly", false);
} else {
//Make the display field read-only
$(inpElemDisp).prop("readonly", true);
}
} else {
if (elm.value != "Other" && !$(elm).attr("keypressOff")) {
$(elm).keypress(function(event) {
console.log("keypress preventd")
event.preventDefault();
})
} else {
$(elm).off("keypress");
$(elm).attr("keypressOff", true);
console.log("keypress event removed")
}
}
}
function resizeElem() {
angular.element(document).ready(function() {
initInpElem();
$(inpElemDisp).width($(elemSel).outerWidth()-20);
})
}
angular.element(document).ready(function(){
initInpElem();
//When the display value changes, then update the hidden text field
inpElemDisp.change(function(){
angular.element(inpElem).controller('ngModel').$setViewValue(inpElemDisp.val());
angular.element(inpElem).controller('ngModel').$render();
});
makeEditable(elemSel);
});
//When field values are initialized, ensure the drop-down list and other fields are synchronized
scope.$on('event:force-model-update', function() {
initInpElem();
//Use the value of the hidden field which is saved in DB to update the values of the other fields
var selectedValue = $(elemSel).find('option[value="' + inpElem.val() + '"]').val();
var selectedText;
if (angular.isUndefined(selectedValue)) {
selectedText = inpElem.val();
} else {
//Update the selected value
if (angular.element(elemSel).controller('ngModel')) {
angular.element(elemSel).controller('ngModel').$setViewValue(selectedValue);
angular.element(elemSel).controller('ngModel').$render();
}
$(elemSel).find('option[value="' + inpElem.val() + '"]').attr('selected', 'selected');
selectedText = $(elemSel).find('option:selected').text()
}
//Update the display value
angular.element(inpElemDisp).controller('ngModel').$setViewValue(selectedText);
angular.element(inpElemDisp).controller('ngModel').$render();
});
$(elemSel).change(function () {
//Everytime the selected value is update, then change the display and hidden value
updateEditable(elemSel);
});
$(elemSel).onPositionChanged(function() {
resizeElem();
})
}
}
});
The above code needs improvement to monitor changes only to the width. I will do that in the next sprint.
Tarek

Email input form not showing/working properly in different browsers

I have a simple form which only has two input controls: a text box for taking emails, and a submit button.
HTML:
<form class="form-wrapper cf">
<input type="text" placeholder="Enter your email here..." required>
<button type="submit">
Submit
</button>
</form>
JSFiddle: http://jsfiddle.net/ahmadka/aDhUL/
Form has issues in different browsers:
Chrome: Works & displays fine.
iPhone: Works & displays fine.
Firefox 22: placeholder text not shown, and cannot type anything in
the textbox too !
Internet Explorer 10: Works fine, but placeholder text is cropped !
How can I make it cross-browser compatible guys ?
I've tried removing the placeholder and required parameters to make it very simple, but still it doesn't work on Firefox ..
I think you try to run "placeholder" in all browser.
then just attach one .js file that as follow it work Fine in all browser.
;(function(window, document, $) {
var isInputSupported = 'placeholder' in document.createElement('input'),
isTextareaSupported = 'placeholder' in document.createElement('textarea'),
prototype = $.fn,
valHooks = $.valHooks,
hooks,
placeholder;
if (isInputSupported && isTextareaSupported) {
placeholder = prototype.placeholder = function() {
return this;
};
placeholder.input = placeholder.textarea = true;
} else {
placeholder = prototype.placeholder = function() {
var $this = this;
$this
.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
.not('.placeholder')
.bind({
'focus.placeholder': clearPlaceholder,
'blur.placeholder': setPlaceholder
})
.data('placeholder-enabled', true)
.trigger('blur.placeholder');
return $this;
};
placeholder.input = isInputSupported;
placeholder.textarea = isTextareaSupported;
hooks = {
'get': function(element) {
var $element = $(element);
return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
},
'set': function(element, value) {
var $element = $(element);
if (!$element.data('placeholder-enabled')) {
return element.value = value;
}
if (value == '') {
element.value = value;
// Issue #56: Setting the placeholder causes problems if the element continues to have focus.
if (element != document.activeElement) {
// We can't use `triggerHandler` here because of dummy text/password inputs :(
setPlaceholder.call(element);
}
} else if ($element.hasClass('placeholder')) {
clearPlaceholder.call(element, true, value) || (element.value = value);
} else {
element.value = value;
}
// `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
return $element;
}
};
isInputSupported || (valHooks.input = hooks);
isTextareaSupported || (valHooks.textarea = hooks);
$(function() {
// Look for forms
$(document).delegate('form', 'submit.placeholder', function() {
// Clear the placeholder values so they don't get submitted
var $inputs = $('.placeholder', this).each(clearPlaceholder);
setTimeout(function() {
$inputs.each(setPlaceholder);
}, 10);
});
});
// Clear placeholder values upon page reload
$(window).bind('beforeunload.placeholder', function() {
$('.placeholder').each(function() {
this.value = '';
});
});
}
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
function clearPlaceholder(event, value) {
var input = this,
$input = $(input);
if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
if ($input.data('placeholder-password')) {
$input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
// If `clearPlaceholder` was called from `$.valHooks.input.set`
if (event === true) {
return $input[0].value = value;
}
$input.focus();
} else {
input.value = '';
$input.removeClass('placeholder');
input == document.activeElement && input.select();
}
}
}
function setPlaceholder() {
var $replacement,
input = this,
$input = $(input),
$origInput = $input,
id = this.id;
if (input.value == '') {
if (input.type == 'password') {
if (!$input.data('placeholder-textinput')) {
try {
$replacement = $input.clone().attr({ 'type': 'text' });
} catch(e) {
$replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
}
$replacement
.removeAttr('name')
.data({
'placeholder-password': true,
'placeholder-id': id
})
.bind('focus.placeholder', clearPlaceholder);
$input
.data({
'placeholder-textinput': $replacement,
'placeholder-id': id
})
.before($replacement);
}
$input = $input.removeAttr('id').hide().prev().attr('id', id).show();
// Note: `$input[0] != input` now!
}
$input.addClass('placeholder');
$input[0].value = $input.attr('placeholder');
} else {
$input.removeClass('placeholder');
}
}
}(this, document, jQuery));
and then just put one script on page.
<script>
$(function() {
$('input, textarea').placeholder();
});
</script>
It Work Fine in All Browser (placeholder)
Actually the problem is with your CSS styling.
You have set the height of the input as 0px. So the input box accepts the input but is not displayed in FF due to the height set to zero.
Your Previous Code is here:
.form-wrapper input {
width: 150px;
height: 0px;
padding: 10px 5px;
New JSFiddle with height set to 10px is here: http://jsfiddle.net/B435n/
And you can use any jQuery plugin for placeholder thing.

How to support placeholder attribute in IE8 and 9

I have a small issue, the placeholder attribute for input boxes is not supported in IE 8-9.
What is the best way to make this support in my project (ASP Net). I am using jQuery.
Need I use some other external tools for it?
Is http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html a good solution?
You could use this jQuery plugin:
https://github.com/mathiasbynens/jquery-placeholder
But your link seems to be also a good solution.
You can use any one of these polyfills:
https://github.com/jamesallardice/Placeholders.js (doesn't support password fields)
https://github.com/chemerisuk/better-placeholder-polyfill
These scripts will add support for the placeholder attribute in browsers that do not support it, and they do not require jQuery!
the $.Browser.msie is not on the latest JQuery anymore...
you have to use the $.support
like below:
<script>
(function ($) {
$.support.placeholder = ('placeholder' in document.createElement('input'));
})(jQuery);
//fix for IE7 and IE8
$(function () {
if (!$.support.placeholder) {
$("[placeholder]").focus(function () {
if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
}).blur(function () {
if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function () {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
});
});
}
});
</script>
if you use jquery you can do like this. from this site Placeholder with Jquery
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
these are the alternate links
Placeholder jquery library
HTML5 polyfills -- go for placeholder section
I had compatibility issues with several plugins I tried, this seems to me to be the simplest way of supporting placeholders on text inputs:
function placeholders(){
//On Focus
$(":text").focus(function(){
//Check to see if the user has modified the input, if not then remove the placeholder text
if($(this).val() == $(this).attr("placeholder")){
$(this).val("");
}
});
//On Blur
$(":text").blur(function(){
//Check to see if the use has modified the input, if not then populate the placeholder back into the input
if( $(this).val() == ""){
$(this).val($(this).attr("placeholder"));
}
});
}
$(function(){
if($.browser.msie && $.browser.version <= 9){
$("[placeholder]").focus(function(){
if($(this).val()==$(this).attr("placeholder")) $(this).val("");
}).blur(function(){
if($(this).val()=="") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function() {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
})
});
}
});
try this
I use thisone, it's only Javascript.
I simply have an input element with a value, and when the user clicks on the input element, it changes it to an input element without a value.
You can easily change the color of the text using CSS. The color of the placeholder is the color in the id #IEinput, and the color your typed text will be is the color in the id #email. Don't use getElementsByClassName, because the versions of IE that don't support a placeholder, don't support getElementsByClassName either!
You can use a placeholder in a password input by setting the type of the original password input to text.
Tinker: http://tinker.io/4f7c5/1
- JSfiddle servers are down!
*sorry for my bad english
JAVASCRIPT
function removeValue() {
document.getElementById('mailcontainer')
.innerHTML = "<input id=\"email\" type=\"text\" name=\"mail\">";
document.getElementById('email').focus(); }
HTML
<span id="mailcontainer">
<input id="IEinput" onfocus="removeValue()" type="text" name="mail" value="mail">
</span>
For others landing here. This is what worked for me:
//jquery polyfill for showing place holders in IE9
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
Just add this in you script.js file.
Courtesy of http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
Since most solutions uses jQuery or are not this satisfying as I wished it to be I wrote a snippet for myself for mootools.
function fix_placeholder(container){
if(container == null) container = document.body;
if(!('placeholder' in document.createElement('input'))){
var inputs = container.getElements('input');
Array.each(inputs, function(input){
var type = input.get('type');
if(type == 'text' || type == 'password'){
var placeholder = input.get('placeholder');
input.set('value', placeholder);
input.addClass('__placeholder');
if(!input.hasEvent('focus', placeholder_focus)){
input.addEvent('focus', placeholder_focus);
}
if(!input.hasEvent('blur', placeholder_blur)){
input.addEvent('blur', placeholder_blur);
}
}
});
}
}
function placeholder_focus(){
var input = $(this);
if(input.get('class').contains('__placeholder') || input.get('value') == ''){
input.removeClass('__placeholder');
input.set('value', '');
}
}
function placeholder_blur(){
var input = $(this);
if(input.get('value') == ''){
input.addClass('__placeholder');
input.set('value', input.get('placeholder'));
}
}
I confess that it looks a bit more MORE than others but it works fine.
__placeholder is a ccs-class to make the color of the placeholder text fancy.
I used the fix_placeholder in window.addEvent('domready', ... and for any additinally added code like popups.
Hope you like it.
Kind regards.
I used the code of this link
http://dipaksblogonline.blogspot.com/2012/02/html5-placeholder-in-ie7-and-ie8-fixed.html
But in browser detection I used:
if (navigator.userAgent.indexOf('MSIE') > -1) {
//Your placeholder support code here...
}
<input type="text" name="Name" value="Name" onfocus="this.value = ''" onblur=" if(this.value = '') { value = 'Name'}" />
Add the below code and it will be done.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="https://code.google.com/p/jquery-placeholder-js/source/browse/trunk/jquery.placeholder.1.3.min.js?r=6"></script>
<script type="text/javascript">
// Mock client code for testing purpose
$(function(){
// Client should be able to add another change event to the textfield
$("input[name='input1']").blur(function(){ alert("Custom event triggered."); });
// Client should be able to set the field's styles, without affecting place holder
$("textarea[name='input4']").css("color", "red");
// Initialize placeholder
$.Placeholder.init();
// or try initialize with parameter
//$.Placeholder.init({ color : 'rgb(255, 255, 0)' });
// call this before form submit if you are submitting by JS
//$.Placeholder.cleanBeforeSubmit();
});
</script>
Download the full code and demo from https://code.google.com/p/jquery-placeholder-js/downloads/detail?name=jquery.placeholder.1.3.zip
Here is a javascript function that will create placeholders for IE 8 and below and it works for passwords as well:
/* Function to add placeholders to form elements on IE 8 and below */
function add_placeholders(fm) {
for (var e = 0; e < document.fm.elements.length; e++) {
if (fm.elements[e].placeholder != undefined &&
document.createElement("input").placeholder == undefined) { // IE 8 and below
fm.elements[e].style.background = "transparent";
var el = document.createElement("span");
el.innerHTML = fm.elements[e].placeholder;
el.style.position = "absolute";
el.style.padding = "2px;";
el.style.zIndex = "-1";
el.style.color = "#999999";
fm.elements[e].parentNode.insertBefore(el, fm.elements[e]);
fm.elements[e].onfocus = function() {
this.style.background = "yellow";
}
fm.elements[e].onblur = function() {
if (this.value == "") this.style.background = "transparent";
else this.style.background = "white";
}
}
}
}
add_placeholders(document.getElementById('fm'))
<form id="fm">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<textarea name="description" placeholder="Description"></textarea>
</form>
<script>
if ($.browser.msie) {
$('input[placeholder]').each(function() {
var input = $(this);
$(input).val(input.attr('placeholder'));
$(input).focus(function() {
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
$(input).blur(function() {
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.val(input.attr('placeholder'));
}
});
});
}
;
</script>

How to create a HTML5 single line contentEditable tab which listens to Enter and Esc

I have a dashboard at work and I want people to be able to change the text on the tabs in order to create categories which fit them best.
I wanted single line text which would disregard changes on Esc or commit the changes on Enter or Blur.
I found the answer but figured I would post in order to help others.
Here is the HTML markup:
<span contenteditable="false"></span>
Here is the jQuery/javascript:
$(document).ready(function() {
$('[contenteditable]').dblclick(function() {
$(this).attr('contenteditable', 'true');
clearSelection();
$(this).trigger('focus');
});
$('[contenteditable]').live('focus', function() {
before = $(this).text();
if($(this).attr('contenteditable') == "true") { $(this).css('border', '1px solid #ffd646'); }
//}).live('blur paste', function() {
}).live('blur', function() {
$(this).attr('contenteditable', 'false');
$(this).css('border', '1px solid #fafafa');
$(this).text($(this).text().replace(/(\r\n|\n|\r)/gm,""));
if (before != $(this).text()) { $(this).trigger('change'); }
}).live('keyup', function(event) {
// ESC=27, Enter=13
if (event.which == 27) {
$(this).text(before);
$(this).trigger('blur');
} else if (event.which == 13) {
$(this).trigger('blur');
}
});
$('[contenteditable]').live('change', function() {
var $thisText = $(this).text();
//Do something with the new value.
});
});
function clearSelection() {
if ( document.selection ) {
document.selection.empty();
} else if ( window.getSelection ) {
window.getSelection().removeAllRanges();
}
}
Hope this helps someone!!!

Generating a stylesheet based on inline HTML styling?

I've been working on styling different parts of my website for a while, however I have yet to put my inline styles into a stylesheet. I was wondering if a tool exists to parse an HTML file and generate a stylesheet from it. For example, here is a snippet of my website:
<div class="block" style="border:1px solid">
<img id="profile-pic" style="float:left;border:0px"/>
</div>
And I would like to be able to generate this:
.block {
border: 1px solid;
}
#profile-pic {
float: left;
border: 0px;
}
Does something like this exist?
Here, I wrote a function to do it (the specificity won't be perfect, but it'll get you started):
function getInlineStyles() {
var stylesList = "",
thisElement,
style,
className,
id;
$("*", "body").each(function () {
thisElement = $(this);
style = thisElement.attr("style");
className = thisElement.attr("class");
id = thisElement.attr("id");
if (id !== undefined) {
stylesList += " #" + id;
}
if (className !== undefined) {
stylesList += " ." + className;
}
if (id !== undefined || className !== undefined) {
stylesList += "{";
}
if (style !== undefined) {
stylesList += style;
}
if (id !== undefined || className !== undefined) {
stylesList += "}";
}
});
return stylesList;
}
Try with Firebug. In CSS part you have something like this:
element.style {
border: 1px solid;
}
for <div class="block">
Just copy this in .block { } and that's it! It's not too easy, but it can help.
No, there isn't such tool. What do you do when there's more than one class? Or a class and an ID? Or an element who's a child of an element with an ID?
No, HTML is to complex to be parsed in this way to create efficient CSS code. You'll need to do so manually.
The general approach on this, is to take an inline-css heavy page, and download it locally. Then, reconstruct the page from scratch. The bright side is that you only need to do the CSS once. Once you have a global stylesheet, the rest of the pages will fall right into place.