HTML5 - How to aply CSS to validator message - html

I'm trying (with no results) to aply a simple custom width to this validator message:
How can i do it ?
UPDATE: I mean, the message which says "Please select an item from the list" we can supose it has, by default, a width=100px . How can i change this default width to 300px?

This question has already been answered. You can find the answer here. For ease of access the code you'll need is below.
::-webkit-validation-bubble
::-webkit-validation-bubble-arrow-clipper
::-webkit-validation-bubble-arrow
::-webkit-validation-bubble-message
This is Chrome's implementation of styling, however it is not officially standard. Hence consider creating your own popup.
Setting content of bubble
Please consider adding what you have already attempted and what results you would expect.
$(document).ready(function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("This field shouldn't be left blank/please select an option!");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})

Related

Is there a way to select an HTML node and copy only the CSS for that node? [duplicate]

I often find nice stylings on the web. To copy the CSS of a DOM element, I inspect that element with Google Chrome Developer Tools, look at the various CSS properties, and copy those manually to my own stylesheets.
Is it possible to easily export all CSS properties of a given DOM element?
Here is the code for an exportStyles() method that should return a CSS string including all inline and external styles for a given element, except default values (which was the main difficulty).
For example: console.log(someElement.exportStyles());
Since you are using Chrome, I did not bother making it compatible with IE.
Actually it just needs that the browsers supports the getComputedStyle(element) method.
Element.prototype.exportStyles = (function () {
// Mapping between tag names and css default values lookup tables. This allows to exclude default values in the result.
var defaultStylesByTagName = {};
// Styles inherited from style sheets will not be rendered for elements with these tag names
var noStyleTags = {"BASE":true,"HEAD":true,"HTML":true,"META":true,"NOFRAME":true,"NOSCRIPT":true,"PARAM":true,"SCRIPT":true,"STYLE":true,"TITLE":true};
// This list determines which css default values lookup tables are precomputed at load time
// Lookup tables for other tag names will be automatically built at runtime if needed
var tagNames = ["A","ABBR","ADDRESS","AREA","ARTICLE","ASIDE","AUDIO","B","BASE","BDI","BDO","BLOCKQUOTE","BODY","BR","BUTTON","CANVAS","CAPTION","CENTER","CITE","CODE","COL","COLGROUP","COMMAND","DATALIST","DD","DEL","DETAILS","DFN","DIV","DL","DT","EM","EMBED","FIELDSET","FIGCAPTION","FIGURE","FONT","FOOTER","FORM","H1","H2","H3","H4","H5","H6","HEAD","HEADER","HGROUP","HR","HTML","I","IFRAME","IMG","INPUT","INS","KBD","KEYGEN","LABEL","LEGEND","LI","LINK","MAP","MARK","MATH","MENU","META","METER","NAV","NOBR","NOSCRIPT","OBJECT","OL","OPTION","OPTGROUP","OUTPUT","P","PARAM","PRE","PROGRESS","Q","RP","RT","RUBY","S","SAMP","SCRIPT","SECTION","SELECT","SMALL","SOURCE","SPAN","STRONG","STYLE","SUB","SUMMARY","SUP","SVG","TABLE","TBODY","TD","TEXTAREA","TFOOT","TH","THEAD","TIME","TITLE","TR","TRACK","U","UL","VAR","VIDEO","WBR"];
// Precompute the lookup tables.
for (var i = 0; i < tagNames.length; i++) {
if(!noStyleTags[tagNames[i]]) {
defaultStylesByTagName[tagNames[i]] = computeDefaultStyleByTagName(tagNames[i]);
}
}
function computeDefaultStyleByTagName(tagName) {
var defaultStyle = {};
var element = document.body.appendChild(document.createElement(tagName));
var computedStyle = getComputedStyle(element);
for (var i = 0; i < computedStyle.length; i++) {
defaultStyle[computedStyle[i]] = computedStyle[computedStyle[i]];
}
document.body.removeChild(element);
return defaultStyle;
}
function getDefaultStyleByTagName(tagName) {
tagName = tagName.toUpperCase();
if (!defaultStylesByTagName[tagName]) {
defaultStylesByTagName[tagName] = computeDefaultStyleByTagName(tagName);
}
return defaultStylesByTagName[tagName];
}
return function exportStyles() {
if (this.nodeType !== Node.ELEMENT_NODE) {
throw new TypeError("The exportStyles method only works on elements, not on " + this.nodeType + " nodes.");
}
if (noStyleTags[this.tagName]) {
throw new TypeError("The exportStyles method does not work on " + this.tagName + " elements.");
}
var styles = {};
var computedStyle = getComputedStyle(this);
var defaultStyle = getDefaultStyleByTagName(this.tagName);
for (var i = 0; i < computedStyle.length; i++) {
var cssPropName = computedStyle[i];
if (computedStyle[cssPropName] !== defaultStyle[cssPropName]) {
styles[cssPropName] = computedStyle[cssPropName];
}
}
var a = ["{"];
for(var i in styles) {
a[a.length] = i + ": " + styles[i] + ";";
}
a[a.length] = "}"
return a.join("\r\n");
}
})();
This code is base on my answer for a slightly related question: Extract the current DOM and print it as a string, with styles intact
I'm quoting Doozer Blake's excellent answer, provided above as a comment. If you like this answer, please upvote his original comment above:
Not a direct answer, but with Chrome Developer Tools, you can click inside Styles or Computed Styles, hit Ctrl+A and then Ctrl+C to copy all the styles in those given areas. It's not perfect in the Style tab because it picks up some extra stuff. Better than selecting them one by one I guess. – Doozer Blake 3 hours ago
You can do the same using Firebug for Firefox, by using Firebug's "Computed" side panel.
There are a few ways to almost do this.
Have a look at FireDiff
Also have a look at cssUpdater This is for local CSS only]
And see this Q for more similar tools: Why can't I save CSS changes in Firebug?
Also this paid product claims to be able to do this: http://www.skybound.ca/

Change CSS of an linked div/id

I link to a page like page.html#id so the page is automatically focused at this id.
How do i do this in CSS that only the div with the id from the URL gets for example a yellow background?
Thanks
Use the :target pseudo selector.
http://css-tricks.com/on-target/
Get the hash value and style it using JavaScript:
if(window.location.hash) {
var hash = window.location.hash.substring(1); //the variable without hash sign.
document.getElementById(hash).style.background = "yellow";
}
Edit - didn't know about :target. That answer is better!
You could listen for the hashchange event, detect the current hash and apply a class to the corresponding element:
window.addEventListener('hashchange', function() {
// Remove .active from any currently active elements
var active = document.getElementsByClassName('active');
for(var i = 0; i < active.length; ++i) {
active[i].classList.remove('active');
}
var id = window.location.hash.substr(1);
document.getElementById(id).classList.add('active');
});
If you need to support browsers that do not support classList, there are plenty of alternatives.
JSFiddle

What is the best way to remove all tabindex attribute to html elements?

What is the best way to remove all tabindex attributes from html elements? GWt seems to put this attribute even it is not set anywhere in the code. It sets tabindex to -1.
I have the code below as working but it is tedious because I have to search every element according to its tag name and that slows the page loading. Any other suggestions? I'd prefer the solution not use javascript, as I am new to it.
NodeList<Element> input = this.getElement().getElementsByTagName("input");
if(input.getLength()>0)
{
for(int i=0; i<=input.getLength(); i++)
{
input.getItem(i).removeAttribute("tabIndex");
}
}
NodeList<Element> div = this.getElement().getElementsByTagName("div");
if(div.getLength()>0)
{
for(int i=0; i<=div.getLength(); i++)
{
div.getItem(i).removeAttribute("tabIndex");
}
}
I'm not entirely sure what you are asking then. You want to remove the tab index attribute. You either:
set the tabindex attribute to -1 manually in the HTML.
use the code you already have.
or use the simplified JQuery version in the other thread.
Perhaps I have misunderstood what you are trying to achieve?
EDIT
Okay perhaps this:
$(document).ready(function(){
$('input').removeAttr("tabindex");
});
This should remove it rather than set it to -1... hopefully. Sorry if I've misunderstood again!
JQuery removeAttr Link
Use querySelectorAll function which Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors.
function removeTagAttibute( attributeName ){
var allTags = '*';
var specificTags = ['ARTICLE', 'INPUT'];
var allelems = document.querySelectorAll( specificTags );
for(i = 0, j = 0; i < allelems.length; i++) {
allelems[i].removeAttribute( attributeName );
}
}
removeTagAttibute( 'tabindex' );
I finally figured it out.
I tried Javascirpt/jquery but they couldn't remove tabindexes because the page was not fully rendered yet - my panels are placed programmatically after window.load. What I did is make use of the RootPanel.class of gwt (which was being used already, but I didn't know).
The task: to get rid of all tabindex with -1 value, add type="tex/javascript" for all script tags, type="text/css" for style tags and out an alt to all img tags. These are all for the sake of html validation.
I am not sure this is the best way, it sure does add up to slow loading, but client is insisting that I do it. So here it is:
RootPanel mainPanel = RootPanel.get(Test_ROOT_PANEL_ID);
Widget widget = (Widget) getEntryView();
mainPanel.add((widget));
// Enable the view disable the loading view. There should always be
// the loading panel to disable.
Element mainPanelelement = DOM.getElementById(Test_ROOT_PANEL_ID);
Element loadingMessage = DOM.getElementById(LOADING_MESSAGE);
Element parent = loadingMessage.getParentElement();
if(parent!=null)
{
//i had to use prev sibling because it is the only way that I know of to access the body //tag that contains the scripts that are being generated by GWT ex.bigdecimal.js
Element body = parent.getPreviousSibling().getParentElement();
if(body!=null)
{
NodeList<Element> elms = body.getElementsByTagName("*");
if(elms.getLength()>0)
{
Element element=null;
for(int i=0; i<=elms.getLength(); i++)
{
if(elms.getItem(i)!=null)
{
element = elms.getItem(i);
if(element.getTagName().compareToIgnoreCase("script")==0)
element.setAttribute("type", "text/javascript");
else if(element.getTagName().compareToIgnoreCase("style")==0)
element.setAttribute("type", "text/css");
else if(element.getTagName().compareToIgnoreCase("img")==0)
{
if(element.getAttribute("alt")=="")
element.setAttribute("alt", element.getAttribute("title")!=" " ? element.getTitle() : " " );
}
else
{
if(element.getTabIndex()<=0)
element.removeAttribute("tabindex");
}
}
}
}
}
}
DOM.setStyleAttribute((com.google.gwt.user.client.Element) loadingMessage, "display", "none");
DOM.setStyleAttribute((com.google.gwt.user.client.Element) mainPanelelement, "display", "inline");
// Change cursor back to default.
RootPanel.getBodyElement().getStyle().setProperty("cursor", "default");
}

IE9 HTML5 placeholder - how are people achieving this?

I'm trying to use the placeholder="xxx" attribute in my web application, and I don't want to have a special visual for IE9. Can people throw out some good suggestions for achieving this functionality in IE9?
I've found a couple links on here but none of the suggested scripts were sufficient... and the answers were from mid-2011, so I figured maybe there is a better solution out there. Perhaps with a widely-adopted jQuery plugin? I do not want to use anything that requires intrusive code such as requiring a certain css class or something.
Thanks.
EDIT - I also need this to work for password input fields.
// the below snippet should work, but isn't.
$(document).ready(function() {
initPlaceholders()();
}
function initPlaceholders() {
$.support.placeholder = false;
var test = document.createElement('input');
if ('placeholder' in test) {
$.support.placeholder = true;
return function() { }
} else {
return function() {
$(function() {
var active = document.activeElement;
$('form').delegate(':text, :password', 'focus', function() {
var _placeholder = $(this).attr('placeholder'),
_val = $(this).val();
if (_placeholder != '' && _val == _placeholder) {
$(this).val('').removeClass('hasPlaceholder');
}
}).delegate(':text, :password', 'blur', function() {
var _placeholder = $(this).attr('placeholder'),
_val = $(this).val();
if (_placeholder != '' && (_val == '' || _val == _placeholder)) {
$(this).val(_placeholder).addClass('hasPlaceholder');
}
}).submit(function() {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
$(':text, :password').blur();
$(active).focus();
});
}
}
}
We just researched the same thing. We decided on reusing this gist, by Aaron McCall, after making some minor changes. The main advantage is that it's simple, easy to understand code:
Remove the kernel and setup_placeholders parts. Just call it immediately in an anonymous function.
Add var before test.
For browsers that support placeholder, it simply falls back to that. It also handles new input elements (note the use of delegate) in existing forms. But does not handle dynamic new form elements. It could probably be modified to do so with jQuery.on.
If you don't like this one, you can use one of the ones here. However, some of them are overcomplicated, or have questionable design decisions like setTimeout for detecting new elements.
Note that it needs to use two pairs of parens, since you're calling an anonymous function, then calling the returned function (this could be factored out differently):
(function () {
// ...
})()();
I wrote a jquery plugin a while back that adds the placeholder support to any browser that does not support it and does nothing in those that do.
Placeholder Plugin
Here's a jQuery plugin that works with password fields as well. It's not as tiny as the code suggested by Matthew but it has a few more fixes in it. I've used this successfully together with H5Validate as well.
http://webcloud.se/code/jQuery-Placeholder/

revealing text within a webpage on link

is there a simple way to reveal text within a webpage using a link without altering the web address or using an iframe? maybe with an 'onclick' function? im pretty new to new code so not sure where to start.. ive attached a picture of what exaclty im after, fairly simple. im already using an iframe as the main interface so another one would get messy in terms of a default menu. there must be a simple fix.. any help would be really appreciated.
thanks, Aaron
Put the text you want to hide until click inside hidden container, like this:
<div id="HiddenTextContainer" style="display: none;">
Hello, I will become visible when you click something else
</div>
Next step is add that JavaScript code to the page, for example inside the <head> section:
function ShowHiddenText() {
document.getElementById("HiddenTextContainer").style.display = "block";
}
And finally have such code:
<span onclick="ShowHiddenText();">click me to show hidden text</span>
Live test case.
Edit: in case you got more than one element to show, you can use the rel attribute:
<span rel="HiddenTextContainer2">click me to show second hidden text</span><br />
Then with pure JavaScript iterate over all elements with that attribute and assign their onclick programmatically:
window.onload = function() {
var elements = document.getElementsByTagName("span");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var id = element.getAttribute("rel") || "";
if (id.length > 0) {
element.onclick = function() {
var oToShow = document.getElementById(this.getAttribute("rel"));
if (oToShow)
oToShow.style.display = "block";
};
}
}
};
When clicked, element with ID the same as the rel value will be displayed.
Updated fiddle.
Edit: to show it in one single container, first have such container:
<div id="HiddenTextContainer"></div>
No need to have it hidden since it's initially empty, then change the code to:
window.onload = function() {
var elements = document.getElementsByTagName("span");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var id = element.getAttribute("rel") || "";
if (id.length > 0) {
element.onclick = function() {
var oToShow = document.getElementById(this.getAttribute("rel"));
if (oToShow)
document.getElementById("HiddenTextContainer").innerHTML = oToShow.innerHTML;
};
}
}
};
Instead of showing the related container, you copy its contents to the "main" container.
Updated jsFiddle.
You have 2 choices for this. The first is to preload everything on the page and then only set the visible property when you click the link. The second is to load it in using something like AJAX and then show it the same way as above.
To show these things look into JQuery: http://jquery.com/
A good tutorial for the second method is here: http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/