January 20, 2013

how to determine whether string is a valid html4 tagName?

Question by cc young

given a string, ‘div’ or ‘abc’, is there any way to determine whether the string is a valid html4 tagName?

tried using document.createElement(), but it’s happy with anything:

document.createElement('trash')
=> <trash></trash>

cannot use HTML<tag>Element. for example

document.createElement('tbody')
=> HTMLTableSelectorElement

Answer by minitech

The best way is to have a list of all valid HTML4 elements and check that. This will give you the right result for “a valid HTML4 element” 100% of the time. From here:

var html4 = ["A","ABBR","ACRONYM","ADDRESS","APPLET","AREA","B","BASE","BASEFONT","BDO","BIG","BLOCKQUOTE","BODY","BR","BUTTON","CAPTION","CENTER","CITE","CODE","COL","COLGROUP","DD","DEL","DFN","DIR","DIV","DL","DT","EM","FIELDSET","FONT","FORM","FRAME","FRAMESET","H1","H2","H3","H4","H5","H6","HEAD","HR","HTML","I","IFRAME","IMG","INPUT","INS","ISINDEX","KBD","LABEL","LEGEND","LI","LINK","MAP","MENU","META","NOFRAMES","NOSCRIPT","OBJECT","OL","OPTGROUP","OPTION","P","PARAM","PRE","Q","S","SAMP","SCRIPT","SELECT","SMALL","SPAN","STRIKE","STRONG","STYLE","SUB","SUP","TABLE","TBODY","TD","TEXTAREA","TFOOT","TH","THEAD","TITLE","TR","TT","U","UL","VAR"];

var valid = html4.indexOf(name.toUpperCase()) !== -1;

(Or, using an object, as @SLaks suggested.)

If you absolutely don’t want to do that for some reason, or didn’t actually mean HTML4, and aren’t worried about IE8- compatibility, then you can do this:

var valid = !(document.createElement(name) instanceof HTMLUnknownElement);

Answer by Starx

A rather simple technique is to define your own set of valid HTML Elements

Array.prototype.contains = function(k) {
   return (this.indexOf(k) > -1;
}
var ValidTags = ['html', 'head', ....];
//Then compare
if(ValidTags.contains('trash')) {
   //Then its valid
}

Detect page zoom change with jQuery in Safari

Question by C.O.

I have a problem with Safari in a web application that contains a position:fixed element. When the page is zoomed out (smaller 100%) things break and would need to be fixed by calling a function. So I’d like to detect the user’s zooming. I found this jQueryPlug-in a while ago:

http://mlntn.com/2008/12/11/javascript-jquery-zoom-event-plugin/

http://mlntn.com/demos/jquery-zoom/

It detects keyboard and mouse events that might lead to a page zoom level change. Fair enough. It works on current FF and IE but not on Safari. Any ideas what could be done to do something simmilar in current WebKit browsers?

Thanks.

Answer by newtron

It’s not a direct duplicate of this question since that deals with Mobile Safari, but the same solution will work.

When you zoom in, window.innerWidth is adjusted, but document.documentElement.clientWidth is not, therefore:

var zoom = document.documentElement.clientWidth / window.innerWidth;

Furthermore, you should be able to use the onresize event handler (or jQuery’s .resize()) to check for this:

var zoom = document.documentElement.clientWidth / window.innerWidth;
$(window).resize(function() {
    var zoomNew = document.documentElement.clientWidth / window.innerWidth;
    if (zoom != zoomNew) {
        // zoom has changed
        // adjust your fixed element
        zoom = zoomNew
    }
});

Answer by Starx

There is a nifty plugin built from yonran that can do the detection. Here is his previously answered question on StackOverflow. It works for most of the browsers. Application is as simple as this:

window.onresize = function onresize() {
  var r = DetectZoom.ratios();
  zoomLevel.innerHTML =
    "Zoom level: " + r.zoom +
    (r.zoom !== r.devicePxPerCssPx
        ? "; device to CSS pixel ratio: " + r.devicePxPerCssPx
        : "");
}

Demo

Catch browser's "zoom" event in JavaScript

Question by user123093

Is it possible to detect, using JavaScript, when the user changes the zoom in a page?
I simply want to catch a “zoom” event and respond to it (similar to window.onresize event).

Thanks.

Answer by Ian Elliott

There’s no way to actively detect if there’s a zoom. I found a good entry here on how you can attempt to implement it.

I’ve found two ways of detecting the
zoom level. One way to detect zoom
level changes relies on the fact that
percentage values are not zoomed. A
percentage value is relative to the
viewport width, and thus unaffected by
page zoom. If you insert two elements,
one with a position in percentages,
and one with the same position in
pixels, they’ll move apart when the
page is zoomed. Find the ratio between
the positions of both elements and
you’ve got the zoom level. See test
case.
http://novemberborn.net/javascript/page-zoom-ff3

You could also do it using the tools of the above post. The problem is you’re more or less making educated guesses on whether or not the page has zoomed. This will work better in some browsers than other.

There’s no way to tell if the page is zoomed if they load your page while zoomed.

Answer by Starx

There is a nifty plugin built from yonran that can do the detection. Here is his previously answered question on StackOverflow. It works for most of the browsers. Application is as simple as this:

window.onresize = function onresize() {
  var r = DetectZoom.ratios();
  zoomLevel.innerHTML =
    "Zoom level: " + r.zoom +
    (r.zoom !== r.devicePxPerCssPx
        ? "; device to CSS pixel ratio: " + r.devicePxPerCssPx
        : "");
}

Demo

January 17, 2013

Forcing <table> Columns to a Fixed Width; Prevent Automatic Expand

Question by Chad Decker

I generally set fixed column widths via CSS with flawless results:

#tableID thead tr th:nth-child(1){width: 75px;} 
#tableID thead tr th:nth-child(2){width: 75px;}
/* etc… */

But now I’m in a situation where I won’t know the desired column widths until runtime. Here’s an excerpt from the code I’m using to dynamically set the column widths:

var tr=$("<tr>");
var colArr=Home.ColDefs[this.statBatchType].colArr;
for(var i=0;i<colArr.length;i++){
    var col=colArr[i];
    tr.append(
        $("<th>")
            .html(col.title)
            .css("width",col.width)
    );
}
this.jqTHead.append(tr);

Sorry this code is a bit out of context but the bottom line is that I’m adding columns, represented by <th> elements, to a table header and setting each one’s width.

What ACTUALLY happens, however, is that Firefox is treating the column width as a minimum and then automatically expanding the column width as the user expands his browser window. Consider a case where my JavaScript code sets the width of each column to 75px. Firefox will ensure each column is at least 75px wide, but if the user maximizes (or enlarges) his browser, provided there is sufficient room, each column will be automatically widened.

This is odd to me since the JavaScript code would seem to be the functional equivalent of what I was doing in CSS. Yet the CSS approach doesn’t cause this odd behavior.

Any thoughts?

Answer by Starx

You can assign a class selector with the required css and then assign it later when you need it on runtime.

.fixed {
   width: 50px;
}

And assign them when you want in run time.

$("th").addClass('fixed');
January 14, 2013

How do I set background color of text only in CSS?

Question by Hithere Paperbag

enter image description here

What I want is for the green background not to be 100% of the page width.
I want it just behind the text.
Html:

<!DOCTYPE html>

<head> 
<link rel="stylesheet" type="text/css" href="style.css">
</head> 

<body> 

<h1>  
The Last Will and Testament of
Eric Jones</h1> 

</body> 

style.css:

h1
{ 
    text-align: center; 
    background-color: green; 
}

Answer by BalusC

Put the text in an inline element, such as a <span>.

<h1><span>The Last Will and Testament of Eric Jones</span></h1>

And then apply the background color on the inline element.

h1 {
    text-align: center; 
}
h1 span { 
    background-color: green; 
}

An inline element is as big as its contents is, so that should do it for you.

Answer by Starx

A very simple trick to do so, is to add a <span> tag and add background color to that. It will look just the way you want it.

<h1>  
    <span>The Last Will and Testament of Eric Jones</span>
</h1> 

And CSS

h1 { text-align: center; }
h1 span { background-color: green; }

WHY?

<span> tag in an inline element tag, so it will only span over the content faking the effect.

...

Please fill the form - I will response as fast as I can!