How to highlight search text in html with the help of js? - javascript

I am passing a very very hard time with JavaScript and I have zero knowledge with jQuery. I am trying to highlight a text from a page or from a body with the help of JavaScript and jQuery.
With hard try, I manage a search code with highlight.
My HTML code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="/javascripts/application.js" type="text/javascript">
</head>
<body>
Search: <input type="text" id="text-search" />
<p>
<b>Demo </b> he new edition of KnowlEdge K12 enables your school with flexibility by wholly automating their administrative and academic processes. With IncTech’s solution for K12 schools, you can. We give you an internal infrastructure so you can share school and student information.
</p>
</body>
My full code with jQuery and JavaScript:
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType == 1 && node.childNodes && !/(script|style) /i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.each(function() {
innerHighlight(this, pat.toUpperCase());
});
};
jQuery.fn.removeHighlight = function() {
function newNormalize(node) {
for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
var child = children[i];
if (child.nodeType == 1) {
newNormalize(child);
continue;
}
if (child.nodeType != 3) { continue; }
var next = child.nextSibling;
if (next == null || next.nodeType != 3) { continue; }
var combined_text = child.nodeValue + next.nodeValue;
new_node = node.ownerDocument.createTextNode(combined_text);
node.insertBefore(new_node, child);
node.removeChild(child);
node.removeChild(next);
i--;
nodeCount--;
}
}
return this.find("span.highlight").each(function() {
var thisParent = this.parentNode;
thisParent.replaceChild(this.firstChild, this);
newNormalize(thisParent);
}).end();
};
$(function() {
$('#text-search').bind('keyup change', function(ev) {
// pull in the new value
var searchTerm = $(this).val();
// remove any old highlighted terms
$('body').removeHighlight();
// disable highlighting if empty
if ( searchTerm ) {
// highlight the new term
$('body').highlight( searchTerm );
}
});
});
.highlight {
background-color: #fff34d;
-moz-border-radius: 5px; /* FF1+ */
-webkit-border-radius: 5px; /* Saf3-4 */
border-radius: 5px; /* Opera 10.5, IE 9, Saf5, Chrome */
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* FF3.5+ */
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Saf3.0+, Chrome */
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Opera 10.5+, IE 9.0 */
}
.highlight {
padding:1px 4px;
margin:0 -4px;
}
Please don't ask me for any kind of more info. Every thing is given in comment section. Guys please please help me.

The only issue i could see in your example is in this line
<script src="/javascripts/application.js" type="text/javascript">
which is looking for this .js and not founding it due to this highlight functions are not getting created.
Try changing it with this and add application.js with different script tag.
<script type="text/javascript">
Working Example
.highlight {
background-color: #fff34d;
-moz-border-radius: 5px; /* FF1+ */
-webkit-border-radius: 5px; /* Saf3-4 */
border-radius: 5px; /* Opera 10.5, IE 9, Saf5, Chrome */
-moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* FF3.5+ */
-webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Saf3.0+, Chrome */
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7); /* Opera 10.5+, IE 9.0 */
}
.highlight {
padding:1px 4px;
margin:0 -4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType == 1 && node.childNodes && !/(script|style) /i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.each(function() {
innerHighlight(this, pat.toUpperCase());
});
};
jQuery.fn.removeHighlight = function() {
function newNormalize(node) {
for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
var child = children[i];
if (child.nodeType == 1) {
newNormalize(child);
continue;
}
if (child.nodeType != 3) { continue; }
var next = child.nextSibling;
if (next == null || next.nodeType != 3) { continue; }
var combined_text = child.nodeValue + next.nodeValue;
new_node = node.ownerDocument.createTextNode(combined_text);
node.insertBefore(new_node, child);
node.removeChild(child);
node.removeChild(next);
i--;
nodeCount--;
}
}
return this.find("span.highlight").each(function() {
var thisParent = this.parentNode;
thisParent.replaceChild(this.firstChild, this);
newNormalize(thisParent);
}).end();
};
</script>
<body>
Search: <input type="text" id="text-search" />
<p>
<b>Demo </b> he new edition of KnowlEdge K12 enables your school with flexibility by wholly automating their administrative and academic processes. With IncTech’s solution for K12 schools, you can. We give you an internal infrastructure so you can share school and student information.
</p>
<script type="text/javascript">
$(function() {
$('#text-search').bind('keyup change', function(ev) {
// pull in the new value
var searchTerm = $(this).val();
// remove any old highlighted terms
$('body').removeHighlight();
// disable highlighting if empty
if ( searchTerm ) {
// highlight the new term
$('body').highlight( searchTerm );
}
});
});
</script>
</body>

Related

Placeholder's text disappears after running this js code

I have a problem while using this (enter multiple emails in an input) that I got from here https://github.com/pierresh/multiple-emails.js/tree/master
the problem is that when I enter a placeholder text onto the input field, it appears for a few second then disappears, I have tried finding out the problems in the js and css file but I still failed to find what causes the placeholder text to disappear.
I tried added this code at a lot of place but the text still disappears
$("#emailInviteList").attr("placeholder", "Friend's email").blur();
this is the multiple-emails.js
(function( $ ){
$.fn.multiple_emails = function(options) {
// Default options
var defaults = {
checkDupEmail: true,
theme: "Bootstrap",
position: "top"
};
// Merge send options with defaults
var settings = $.extend( {}, defaults, options );
var deleteIconHTML = "";
if (settings.theme.toLowerCase() == "Bootstrap".toLowerCase())
{
deleteIconHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
else if (settings.theme.toLowerCase() == "SemanticUI".toLowerCase() || settings.theme.toLowerCase() == "Semantic-UI".toLowerCase() || settings.theme.toLowerCase() == "Semantic UI".toLowerCase()) {
deleteIconHTML = '<i class="remove icon"></i>';
}
else if (settings.theme.toLowerCase() == "Basic".toLowerCase()) {
//Default which you should use if you don't use Bootstrap, SemanticUI, or other CSS frameworks
deleteIconHTML = '<i class="basicdeleteicon">Remove</i>';
}
return this.each(function() {
//$orig refers to the input HTML node
var $orig = $(this);
var $list = $('<ul class="multiple_emails-ul" />'); // create html elements - list of email addresses as unordered list
if ($(this).val() != '' && IsJsonString($(this).val())) {
$.each(jQuery.parseJSON($(this).val()), function( index, val ) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + val.toLowerCase() + '">' + val + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
});
}
var $input = $('<input type="text" class="multiple_emails-input text-left" />').on('keyup', function(e) { // input
$(this).removeClass('multiple_emails-error');
var input_length = $(this).val().length;
var keynum;
if(window.event){ // IE
keynum = e.keyCode;
}
else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
//if(event.which == 8 && input_length == 0) { $list.find('li').last().remove(); } //Removes last item on backspace with no input
// Supported key press is tab, enter, space or comma, there is no support for semi-colon since the keyCode differs in various browsers
if(keynum == 9 || keynum == 32 || keynum == 188) {
display_email($(this), settings.checkDupEmail);
}
else if (keynum == 13) {
display_email($(this), settings.checkDupEmail);
//Prevents enter key default
//This is to prevent the form from submitting with the submit button
//when you press enter in the email textbox
e.preventDefault();
}
}).on('blur', function(event){
if ($(this).val() != '') { display_email($(this), settings.checkDupEmail); }
});
var $container = $('<div class="multiple_emails-container" />').click(function() { $input.focus(); } ); // container div
// insert elements into DOM
if (settings.position.toLowerCase() === "top")
$container.append($list).append($input).insertAfter($(this));
else
$container.append($input).append($list).insertBefore($(this));
/*
t is the text input device.
Value of the input could be a long line of copy-pasted emails, not just a single email.
As such, the string is tokenized, with each token validated individually.
If the dupEmailCheck variable is set to true, scans for duplicate emails, and invalidates input if found.
Otherwise allows emails to have duplicated values if false.
*/
function display_email(t, dupEmailCheck) {
//Remove space, comma and semi-colon from beginning and end of string
//Does not remove inside the string as the email will need to be tokenized using space, comma and semi-colon
var arr = t.val().trim().replace(/^,|,$/g , '').replace(/^;|;$/g , '');
//Remove the double quote
arr = arr.replace(/"/g,"");
//Split the string into an array, with the space, comma, and semi-colon as the separator
arr = arr.split(/[\s,;]+/);
var errorEmails = new Array(); //New array to contain the errors
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
for (var i = 0; i < arr.length; i++) {
//Check if the email is already added, only if dupEmailCheck is set to true
if ( dupEmailCheck === true && $orig.val().indexOf(arr[i]) != -1 ) {
if (arr[i] && arr[i].length > 0) {
new function () {
var existingElement = $list.find('.email_name[data-email=' + arr[i].toLowerCase().replace('.', '\\.').replace('#', '\\#') + ']');
existingElement.css('font-weight', 'bold');
setTimeout(function() { existingElement.css('font-weight', ''); }, 1500);
}(); // Use a IIFE function to create a new scope so existingElement won't be overriden
}
}
else if (pattern.test(arr[i]) == true) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + arr[i].toLowerCase() + '">' + arr[i] + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
}
else
errorEmails.push(arr[i]);
}
// If erroneous emails found, or if duplicate email found
if(errorEmails.length > 0)
t.val(errorEmails.join("; ")).addClass('multiple_emails-error');
else
t.val("");
refresh_emails ();
}
function refresh_emails () {
var emails = new Array();
var container = $orig.siblings('.multiple_emails-container');
container.find('.multiple_emails-email span.email_name').each(function() { emails.push($(this).html()); });
$orig.val(JSON.stringify(emails)).trigger('change');
}
function IsJsonString(str) {
try { JSON.parse(str); }
catch (e) { return false; }
return true;
}
return $(this).hide();
});
};
})(jQuery);
this is the multiple-emails.css
.multiple_emails-container {
border:1px #ccc solid;
border-radius: 4px;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
padding:0; margin: 0; cursor:text; width:100%;
padding-top: 5px;
background-color: white;
}
.multiple_emails-container input {
clear:both;
width:100%;
height: 30px;
text-align: center;
border:0;
outline: none;
margin-bottom:3px;
padding-left: 5px;
box-sizing: border-box;
}
.multiple_emails-container input{
border: 0 !important;
}
.multiple_emails-container input.multiple_emails-error {
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px red !important;
outline: thin auto red !important;
}
.multiple_emails-container ul {
list-style-type:none;
padding-left: 0;
}
.multiple_emails-email {
margin: 3px 5px 3px 5px;
padding: 3px 5px 3px 5px;
border:1px #BBD8FB solid;
border-radius: 3px;
background: #F3F7FD;
}
.multiple_emails-close {
float:left;
margin:0 3px;
}
this is part of my code in the html file
<script type="text/javascript">
$(function() {
$('#emailInviteList').multiple_emails({position: "bottom"});
});
</script>
<div class='form-group'>
<input type='email' id='emailInviteList' name='emailInviteList' class="form-control" placeholder="Friend's Email">
</div>
Script is creating another textfield which does not have placeholder attribute, below is updated snippet I have just added placeholder="Friend\'s Email" in input var $input.
(function( $ ){
$.fn.multiple_emails = function(options) {
// Default options
var defaults = {
checkDupEmail: true,
theme: "Bootstrap",
position: "top"
};
// Merge send options with defaults
var settings = $.extend( {}, defaults, options );
var deleteIconHTML = "";
if (settings.theme.toLowerCase() == "Bootstrap".toLowerCase())
{
deleteIconHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
else if (settings.theme.toLowerCase() == "SemanticUI".toLowerCase() || settings.theme.toLowerCase() == "Semantic-UI".toLowerCase() || settings.theme.toLowerCase() == "Semantic UI".toLowerCase()) {
deleteIconHTML = '<i class="remove icon"></i>';
}
else if (settings.theme.toLowerCase() == "Basic".toLowerCase()) {
//Default which you should use if you don't use Bootstrap, SemanticUI, or other CSS frameworks
deleteIconHTML = '<i class="basicdeleteicon">Remove</i>';
}
return this.each(function() {
//$orig refers to the input HTML node
var $orig = $(this);
var $list = $('<ul class="multiple_emails-ul" />'); // create html elements - list of email addresses as unordered list
if ($(this).val() != '' && IsJsonString($(this).val())) {
$.each(jQuery.parseJSON($(this).val()), function( index, val ) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + val.toLowerCase() + '">' + val + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
});
}
var $input = $('<input type="text" class="multiple_emails-input text-left" placeholder="Friend\'s Email" />').on('keyup', function(e) { // input
$(this).removeClass('multiple_emails-error');
var input_length = $(this).val().length;
var keynum;
if(window.event){ // IE
keynum = e.keyCode;
}
else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
//if(event.which == 8 && input_length == 0) { $list.find('li').last().remove(); } //Removes last item on backspace with no input
// Supported key press is tab, enter, space or comma, there is no support for semi-colon since the keyCode differs in various browsers
if(keynum == 9 || keynum == 32 || keynum == 188) {
display_email($(this), settings.checkDupEmail);
}
else if (keynum == 13) {
display_email($(this), settings.checkDupEmail);
//Prevents enter key default
//This is to prevent the form from submitting with the submit button
//when you press enter in the email textbox
e.preventDefault();
}
}).on('blur', function(event){
if ($(this).val() != '') { display_email($(this), settings.checkDupEmail); }
});
var $container = $('<div class="multiple_emails-container" />').click(function() { $input.focus(); } ); // container div
// insert elements into DOM
if (settings.position.toLowerCase() === "top")
$container.append($list).append($input).insertAfter($(this));
else
$container.append($input).append($list).insertBefore($(this));
/*
t is the text input device.
Value of the input could be a long line of copy-pasted emails, not just a single email.
As such, the string is tokenized, with each token validated individually.
If the dupEmailCheck variable is set to true, scans for duplicate emails, and invalidates input if found.
Otherwise allows emails to have duplicated values if false.
*/
function display_email(t, dupEmailCheck) {
//Remove space, comma and semi-colon from beginning and end of string
//Does not remove inside the string as the email will need to be tokenized using space, comma and semi-colon
var arr = t.val().trim().replace(/^,|,$/g , '').replace(/^;|;$/g , '');
//Remove the double quote
arr = arr.replace(/"/g,"");
//Split the string into an array, with the space, comma, and semi-colon as the separator
arr = arr.split(/[\s,;]+/);
var errorEmails = new Array(); //New array to contain the errors
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
for (var i = 0; i < arr.length; i++) {
//Check if the email is already added, only if dupEmailCheck is set to true
if ( dupEmailCheck === true && $orig.val().indexOf(arr[i]) != -1 ) {
if (arr[i] && arr[i].length > 0) {
new function () {
var existingElement = $list.find('.email_name[data-email=' + arr[i].toLowerCase().replace('.', '\\.').replace('#', '\\#') + ']');
existingElement.css('font-weight', 'bold');
setTimeout(function() { existingElement.css('font-weight', ''); }, 1500);
}(); // Use a IIFE function to create a new scope so existingElement won't be overriden
}
}
else if (pattern.test(arr[i]) == true) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + arr[i].toLowerCase() + '">' + arr[i] + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
}
else
errorEmails.push(arr[i]);
}
// If erroneous emails found, or if duplicate email found
if(errorEmails.length > 0)
t.val(errorEmails.join("; ")).addClass('multiple_emails-error');
else
t.val("");
refresh_emails ();
}
function refresh_emails () {
var emails = new Array();
var container = $orig.siblings('.multiple_emails-container');
container.find('.multiple_emails-email span.email_name').each(function() { emails.push($(this).html()); });
$orig.val(JSON.stringify(emails)).trigger('change');
}
function IsJsonString(str) {
try { JSON.parse(str); }
catch (e) { return false; }
return true;
}
return $(this).hide();
});
};
})(jQuery);
.multiple_emails-container {
border:1px #ccc solid;
border-radius: 4px;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
padding:0; margin: 0; cursor:text; width:100%;
padding-top: 5px;
background-color: white;
}
.multiple_emails-container input {
clear:both;
width:100%;
height: 30px;
text-align: center;
border:0;
outline: none;
margin-bottom:3px;
padding-left: 5px;
box-sizing: border-box;
}
.multiple_emails-container input{
border: 0 !important;
}
.multiple_emails-container input.multiple_emails-error {
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px red !important;
outline: thin auto red !important;
}
.multiple_emails-container ul {
list-style-type:none;
padding-left: 0;
}
.multiple_emails-email {
margin: 3px 5px 3px 5px;
padding: 3px 5px 3px 5px;
border:1px #BBD8FB solid;
border-radius: 3px;
background: #F3F7FD;
}
.multiple_emails-close {
float:left;
margin:0 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#emailInviteList').multiple_emails({position: "bottom"});
});
</script>
<div class='form-group'>
<input type='email' id='emailInviteList' name='emailInviteList' class="form-control" placeholder="Friend's Email">
</div>

Calculate the word amount from an <input>?

The following code converts text into equal paragraphs, based on the users input character amount.
Is it possible for the input box to calculate the amount of words for each paragraph instead of being based on the character amount?
JSFiddle
If an updated fiddle could please be provided, would be much appreciated, as I am still new to coding.
Thank You!
$(function() {
$('select').on('change', function() {
//Lets target the parent element, instead of P. P will inherit it's font size (css)
var targets = $('#content'),
property = this.dataset.property;
targets.css(property, this.value);
sameheight('#content p');
}).prop('selectedIndex', 0);
});
var btn = document.getElementById('go'),
textarea = document.getElementById('textarea1'),
content = document.getElementById('content');
chunkSize = 100;
btn.addEventListener('click', initialDistribute);
content.addEventListener('keyup', handleKey);
content.addEventListener('paste', handlePaste);
function initialDistribute() {
custom = parseInt(document.getElementById("custom").value);
chunkSize = (custom>0)?custom:chunkSize;
var text = textarea.value;
while (content.hasChildNodes()) {
content.removeChild(content.lastChild);
}
rearrange(text);
}
function rearrange(text) {
var chunks = splitText(text, false);
chunks.forEach(function(str, idx) {
para = document.createElement('P');
para.classList.add("Paragraph_CSS");
para.setAttribute('contenteditable', true);
para.textContent = str;
content.appendChild(para);
});
sameheight('#content p');
}
function handleKey(e) {
var para = e.target,
position,
key, fragment, overflow, remainingText;
key = e.which || e.keyCode || 0;
if (para.tagName != 'P') {
return;
}
if (key != 13 && key != 8) {
redistributeAuto(para);
return;
}
position = window.getSelection().getRangeAt(0).startOffset;
if (key == 13) {
fragment = para.lastChild;
overflow = fragment.textContent;
fragment.parentNode.removeChild(fragment);
remainingText = overflow + removeSiblings(para, false);
rearrange(remainingText);
}
if (key == 8 && para.previousElementSibling && position == 0) {
fragment = para.previousElementSibling;
remainingText = removeSiblings(fragment, true);
rearrange(remainingText);
}
}
function handlePaste(e) {
if (e.target.tagName != 'P') {
return;
}
overflow = e.target.textContent + removeSiblings(fragment, true);
rearrange(remainingText);
}
function redistributeAuto(para) {
var text = para.textContent,
fullText;
if (text.length > chunkSize) {
fullText = removeSiblings(para, true);
}
rearrange(fullText);
}
function removeSiblings(elem, includeCurrent) {
var text = '',
next;
if (includeCurrent && !elem.previousElementSibling) {
parent = elem.parentNode;
text = parent.textContent;
while (parent.hasChildNodes()) {
parent.removeChild(parent.lastChild);
}
} else {
elem = includeCurrent ? elem.previousElementSibling : elem;
while (next = elem.nextSibling) {
text += next.textContent;
elem.parentNode.removeChild(next);
}
}
return text;
}
function splitText(text, useRegex) {
var chunks = [],
i, textSize, boundary = 0;
if (useRegex) {
var regex = new RegExp('.{1,' + chunkSize + '}\\b', 'g');
chunks = text.match(regex) || [];
} else {
for (i = 0, textSize = text.length; i < textSize; i = boundary) {
boundary = i + chunkSize;
if (boundary <= textSize && text.charAt(boundary) == ' ') {
chunks.push(text.substring(i, boundary));
} else {
while (boundary <= textSize && text.charAt(boundary) != ' ') {
boundary++;
}
chunks.push(text.substring(i, boundary));
}
}
}
return chunks;
}
#text_land {
border: 1px solid #ccc;
padding: 25px;
margin-bottom: 30px;
}
textarea {
width: 95%;
}
label {
display: block;
width: 50%;
clear: both;
margin: 0 0 .5em;
}
label select {
width: 50%;
float: right;
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: monospace;
font-size: 1em;
}
h3 {
margin: 1.2em 0;
}
div {
margin: 1.2em;
}
textarea {
width: 100%;
}
button {
padding: .5em;
}
p {
/*Here the sliles for OTHER paragraphs*/
}
#content p {
font-size: inherit;
/*So it gets the font size set on the #content div*/
padding: 1.2em .5em;
margin: 1.4em 0;
border: 1px dashed #aaa;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Import Text below, then press the button</h3>
<textarea id="textarea1" placeholder="Type text here, then press the button below." rows="5">
</textarea>
<input style="width:200px;" id="custom" placeholder="Custom Characters per box">
<br>
<button style="width:200px;" id="go">Divide Text into Paragraphs</button>
</div>
<div>
<h3 align="right">Divided Text Will Appear Below:</h3>
<hr>
<div id="content"></div>
</div>
How about this? It uses jQuery, but as you used the library in your original submission, I hope that won't be an issue:
HTML
<textarea id="input"></textarea>
<br/>
<button id='divide'>Divide</button>
<div id="paras"></div>
CSS
#input {
resize: none;
height: 200px;
width: 100%;
}
JS
$(function() {
$("#divide").click(function() {
var text = $("#input").val();
var wpp = 10 // words per paragraph
var words = text.split(" ");
var paras = [];
for (i = 0; i < words.length; i += wpp) {
paras.push(words.slice(i, i + wpp).join(" "));
}
$.each(paras, function(i, para) {
$("#paras").append("<p>" + para + "</p>");
});
});
})
JSFiddle

javascript:window.print() not showing barcode for printing

I am making Mean Stack App in which I need to print barcode, I am using an angular js directive for generating code 128 barcode, and it is generating well, but when I click print button (javascript:window.print()) it is not showing the barcode in printing window neither in PDF,
Here is my directive,
.directive('barcodeGenerator', [function() {
var Barcode = (function () {
var barcode = {
settings: {
barWidth: 1,
barHeight: 50,
moduleSize: 5,
showHRI: false,
addQuietZone: true,
marginHRI: 5,
bgColor: "#FFFFFF",
color: "#000000",
fontSize: 10,
posX: 0,
posY: 0
},
intval: function(val) {
var type = typeof(val);
if ( type == 'string' ) {
val = val.replace(/[^0-9-.]/g, "");
val = parseInt(val * 1, 10);
return isNaN(val) || !isFinite(val)? 0: val;
}
return type == 'number' && isFinite(val)? Math.floor(val): 0;
},
code128: {
encoding:[
"11011001100", "11001101100", "11001100110", "10010011000",
"10010001100", "10001001100", "10011001000", "10011000100",
"10001100100", "11001001000", "11001000100", "11000100100",
"10110011100", "10011011100", "10011001110", "10111001100",
"10011101100", "10011100110", "11001110010", "11001011100",
"11001001110", "11011100100", "11001110100", "11101101110",
"11101001100", "11100101100", "11100100110", "11101100100",
"11100110100", "11100110010", "11011011000", "11011000110",
"11000110110", "10100011000", "10001011000", "10001000110",
"10110001000", "10001101000", "10001100010", "11010001000",
"11000101000", "11000100010", "10110111000", "10110001110",
"10001101110", "10111011000", "10111000110", "10001110110",
"11101110110", "11010001110", "11000101110", "11011101000",
"11011100010", "11011101110", "11101011000", "11101000110",
"11100010110", "11101101000", "11101100010", "11100011010",
"11101111010", "11001000010", "11110001010", "10100110000",
"10100001100", "10010110000", "10010000110", "10000101100",
"10000100110", "10110010000", "10110000100", "10011010000",
"10011000010", "10000110100", "10000110010", "11000010010",
"11001010000", "11110111010", "11000010100", "10001111010",
"10100111100", "10010111100", "10010011110", "10111100100",
"10011110100", "10011110010", "11110100100", "11110010100",
"11110010010", "11011011110", "11011110110", "11110110110",
"10101111000", "10100011110", "10001011110", "10111101000",
"10111100010", "11110101000", "11110100010", "10111011110",
"10111101110", "11101011110", "11110101110", "11010000100",
"11010010000", "11010011100", "11000111010"
],
getDigit: function(code) {
var tableB = " !\"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
var result = "";
var sum = 0;
var isum = 0;
var i = 0;
var j = 0;
var value = 0;
// check each characters
for(i=0; i<code.length; i++){
if (tableB.indexOf(code.charAt(i)) == -1){
return("");
}
}
// check firsts characters : start with C table only if enought numeric
var tableCActivated = code.length > 1;
var c = '';
for (i=0; i<3 && i<code.length; i++) {
c = code.charAt(i);
tableCActivated &= c >= '0' && c <= '9';
}
sum = tableCActivated ? 105 : 104;
// start : [105] : C table or [104] : B table
result = this.encoding[ sum ];
i = 0;
while ( i < code.length ) {
if ( !tableCActivated) {
j = 0;
// check next character to activate C table if interresting
while ( (i + j < code.length) && (code.charAt(i+j) >= '0') && (code.charAt(i+j) <= '9') ) {
j++;
}
// 6 min everywhere or 4 mini at the end
tableCActivated = (j > 5) || ((i + j - 1 == code.length) && (j > 3));
if ( tableCActivated ){
result += this.encoding[ 99 ]; // C table
sum += ++isum * 99;
} // 2 min for table C so need table B
} else if ( (i == code.length) || (code.charAt(i) < '0') || (code.charAt(i) > '9') || (code.charAt(i+1) < '0') || (code.charAt(i+1) > '9') ) {
tableCActivated = false;
result += this.encoding[ 100 ]; // B table
sum += ++isum * 100;
}
if ( tableCActivated ) {
value = barcode.intval(code.charAt(i) + code.charAt(i+1)); // Add two characters (numeric)
i += 2;
} else {
value = tableB.indexOf( code.charAt(i) ); // Add one character
i += 1;
}
result += this.encoding[ value ];
sum += ++isum * value;
}
result += this.encoding[sum % 103];// Add CRC
result += this.encoding[106];// Stop
result += "11";// Termination bar
return(result);
}
},
bitStringTo2DArray: function( digit) {//convert a bit string to an array of array of bit char
var d = [];
d[0] = [];
for ( var i=0; i<digit.length; i++) {
d[0][i] = digit.charAt(i);
}
return(d);
},
digitToCssRenderer: function( $container, settings, digit, hri, mw, mh, type) {// css barcode renderer
var lines = digit.length;
var columns = digit[0].length;
var content = "";
var len, current;
var bar0 = "<div class='w w%s' ></div>";
var bar1 = "<div class='b b%s' ></div>";
for ( var y=0, x; y<lines; y++) {
len = 0;
current = digit[y][0];
for ( x=0; x<columns; x++){
if ( current == digit[y][x] ) {
len++;
} else {
content += (current == '0'? bar0: bar1).replace("%s", len * mw);
current = digit[y][x];
len=1;
}
}
if ( len > 0) {
content += (current == '0'? bar0: bar1).replace("%s", len * mw);
}
}
if ( settings.showHRI) {
content += "<div style=\"clear:both; width: 100%; background-color: " + settings.bgColor + "; color: " + settings.color + "; text-align: center; font-size: " + settings.fontSize + "px; margin-top: " + settings.marginHRI + "px;\">"+hri+"</div>";
}
var div = document.createElement('DIV');
div.innerHTML = content;
div.className = 'barcode '+ type +' clearfix-child';
return div;
},
digitToCss: function($container, settings, digit, hri, type) {// css 1D barcode renderer
var w = barcode.intval(settings.barWidth);
var h = barcode.intval(settings.barHeight);
return this.digitToCssRenderer($container, settings, this.bitStringTo2DArray(digit), hri, w, h, type);
}
};
var generate = function(datas, type, settings) {
var
digit = "",
hri = "",
code = "",
crc = true,
rect = false,
b2d = false
;
if ( typeof(datas) == "string") {
code = datas;
} else if (typeof(datas) == "object") {
code = typeof(datas.code) == "string" ? datas.code : "";
crc = typeof(datas.crc) != "undefined" ? datas.crc : true;
rect = typeof(datas.rect) != "undefined" ? datas.rect : false;
}
if (code == "") {
return(false);
}
if (typeof(settings) == "undefined") {
settings = [];
}
for( var name in barcode.settings) {
if ( settings[name] == undefined) {
settings[name] = barcode.settings[name];
}
}
switch (type) {
case "std25":
case "int25": {
digit = barcode.i25.getDigit(code, crc, type);
hri = barcode.i25.compute(code, crc, type);
break;
}
case "ean8":
case "ean13": {
digit = barcode.ean.getDigit(code, type);
hri = barcode.ean.compute(code, type);
break;
}
case "upc": {
digit = barcode.upc.getDigit(code);
hri = barcode.upc.compute(code);
break;
}
case "code11": {
digit = barcode.code11.getDigit(code);
hri = code;
break;
}
case "code39": {
digit = barcode.code39.getDigit(code);
hri = code;
break;
}
case "code93": {
digit = barcode.code93.getDigit(code, crc);
hri = code;
break;
}
case "code128": {
digit = barcode.code128.getDigit(code);
hri = code;
break;
}
case "codabar": {
digit = barcode.codabar.getDigit(code);
hri = code;
break;
}
case "msi": {
digit = barcode.msi.getDigit(code, crc);
hri = barcode.msi.compute(code, crc);
break;
}
case "datamatrix": {
digit = barcode.datamatrix.getDigit(code, rect);
hri = code;
b2d = true;
break;
}
}
if ( digit.length == 0) {
return this;
}
if ( !b2d && settings.addQuietZone) {
digit = "0000000000" + digit + "0000000000";
}
var fname = 'digitToCss' + (b2d ? '2D' : '');
return barcode[fname](this, settings, digit, hri, type);
};
return generate;
}());
return {
link: function(scope, element, attrs) {
attrs.$observe('barcodeGenerator', function(value){
var code = Barcode(value, "code128",{barWidth:2}),
code_wrapper = angular.element("<div class='barcode code128'></div>")
code_wrapper.append(code);
angular.element(element).html('').append(code_wrapper);
});
}
}
And here is barcode generating code,
<div ng-model='myInput' barcode-generator="{{myInput}}" style="height:208px;">
</div>
Here are the screenshots
It shows barcode on the page
But not shows up while printing
It's because some browsers has turned off rendering background-color in print mode by default. You won't force all users to mess up with browser settings, but you can replace background-color with border-width like this:
<style type="text/css" media="print">
.barcode.code128 > div.b {
border-style: solid !important;
border-color: #000000 !important;
}
.barcode.code128 .b1 {
width: 0px !important;
border-width: 0px 0px 0px 1px !important;
}
.barcode.code128 .b2 {
width: 0px !important;
border-width: 0px 0px 0px 2px !important;
}
.barcode.code128 .b3 {
width: 0px !important;
border-width: 0px 0px 0px 3px !important;
}
.barcode.code128 .b4 {
width: 0px !important;
border-width: 0px 0px 0px 4px !important;
}
.barcode.code128 .b5 {
width: 0px !important;
border-width: 0px 0px 0px 5px !important;
}
.barcode.code128 .b6 {
width: 0px !important;
border-width: 0px 0px 0px 6px !important;
}
.barcode.code128 .b7 {
width: 0px !important;
border-width: 0px 0px 0px 7px !important;
}
.barcode.code128 .b8 {
width: 0px !important;
border-width: 0px 0px 0px 8px !important;
}
.barcode.code128 .b9 {
width: 0px !important;
border-width: 0px 0px 0px 9px !important;
}
.barcode.code128 .b10 {
width: 0px !important;
border-width: 0px 0px 0px 10px !important;
}

javascript game ( 3 in line ) line check logic

i've been in a battle to sort this problem since yesterday and i fear that i've gotten tunnel vision.
The game:
first player to make a line of 3 of a kind (xxx or 000) wins.
http://jsfiddle.net/brunobliss/YANAW/
The catch:
Only the first horizontal line is working!!! I can make it all work using a lot of IFS but repeating the same code over and over again is often a good indicator that i'm doing somethin wrong
The problem:
bruno.checkWin(); will check if there's a line or not, the guy who presented me this game chalenge told me that it is possible to check the lines with a for loop and that i should use it instead of IFS. I can't solve this without IFS unfortunately...
<!doctype html>
<html>
<head>
<meta charset="iso-8859-1">
<title> </title>
<style>
#jogo {
border: #000 1px solid;
width: 150px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -75px;
margin-top: -75px;
}
#jogo div {
display: inline-block;
vertical-align: top;
width: 28px;
height: 28px;
padding: 10px;
font-size: 20px;
border: #000 1px solid;
border-collapse: collapse;
text-align: center;
}
#reset {
font-family: Verdana;
width: 153px;
height: 30px;
background-color: black;
color: white;
text-align: center;
cursor: pointer;
left: 50%;
top: 50%;
position: absolute;
margin-left: -76px;
margin-top: 100px;
}
</style>
<script> </script>
</head>
<body>
<div id="jogo"> </div>
<div id="reset"> RESET </div>
<script>
var ultimo = "0";
var reset = document.getElementById('reset');
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
var bruno = {
init: function () {
var jogo = document.getElementById('jogo');
for ( i = 0 ; i < 9 ; i++ ) {
var cell = document.createElement('div');
cell.onclick = function () {
// variavel publica dentro do obj?
ultimo = (ultimo == "x") ? 0 : "x";
this.innerHTML = ultimo;
bruno.checkWin();
};
jogo.appendChild(cell);
}
},
checkWin: function () {
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
// as diagonais nao verificar por loop
for ( i = 0 ; i < cell.length ; i=i+4 ) {
switch(i) {
case 0:
if (cell[0].innerHTML != '') {
bruno.checkFirst();
}
case 4:
if (cell[4].innerHTML != '') {
bruno.checkFirst();
}
case 8:
if (cell[8].innerHTML != '') {
bruno.checkFirst();
}
}
/*
} else
if (i == 4 && cell[4].innerHTML != '') {
bruno.checkCenter();
} else
if (i == 8 && cell[8].innerHTML != '') {
bruno.checkLast();
}*/
}
},
reset: function () {
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
for ( j = 0 ; j < cell.length ; j++ ) {
cell[j].innerHTML = "";
}
},
checkFirst: function () {
if (cell[0].innerHTML == cell[1].innerHTML && cell[1].innerHTML == cell[2].innerHTML) {
alert("linha horizontal");
return false;
} else
if (cell[0].innerHTML == cell[3].innerHTML && cell[3].innerHTML == cell[6].innerHTML) {
alert("linha vertical");
return false;
}
},
checkMiddle: function () {
// check vertical and horizontal lines from the center
},
checkLast: function () {
// check last horizontal and right edge vertical
}
};
window.onload = function () {
bruno.init();
};
reset.onclick = function () {
bruno.reset();
};
</script>
</body>
</html>
I came up with a more 'compact' version of your code. No switch statements. Have a look:
http://jsfiddle.net/YANAW/1/
Here's the code, for those who prefer to read it here. Important/updated functions are checkWin() and checkCells().
var bruno = {
init: function () {
var jogo = document.getElementById('jogo');
for ( i = 0 ; i < 9 ; i++ ) {
var cell = document.createElement('div');
cell.onclick = function () {
// variavel publica dentro do obj?
ultimo = (ultimo == "x") ? 0 : "x";
this.innerHTML = ultimo;
bruno.checkWin();
};
jogo.appendChild(cell);
}
},
checkWin: function () {
var jogo = document.getElementById('jogo');
var cells = jogo.getElementsByTagName('div');
// Scan through every cell
var numRows = 3;
var numColumns = 3;
for (var i = 0; i < cells.length; i++)
{
// Determine cell's position
var isHorizontalFirstCell = ((i % numColumns) === 0);
var isVerticalFirstCell = (i < numColumns);
var isTopLeftCorner = (i == 0);
var isTopRightCorner = (i == 2);
// Check for horizontal matches
if (isHorizontalFirstCell
&& bruno.checkCells(
cells, i,
(i + 3), 1))
{
alert('Horizontal');
}
// Check for vertical matches
if (isVerticalFirstCell
&& bruno.checkCells(
cells, i,
(i + 7), 3))
{
alert('Vertical');
}
// Check for diagonal matches
if (isTopLeftCorner
&& bruno.checkCells(
cells, i,
(i + 9), 4))
{
alert('Diagonal');
}
if (isTopRightCorner
&& bruno.checkCells(
cells, i,
(i + 5), 2))
{
alert('Diagonal');
}
}
},
reset: function () {
var jogo = document.getElementById('jogo');
var cell = jogo.getElementsByTagName('div');
for ( j = 0 ; j < cell.length ; j++ ) {
cell[j].innerHTML = "";
}
},
checkCells: function(cells, index, limit, step) {
var sequenceChar = null;
for (var i = index; i < limit; i += step)
{
// Return false immediately if one
// of the cells in the sequence is empty
if (!cells[i].innerHTML)
return false;
// If this is the first cell we're checking,
// store the character(s) it holds.
if (sequenceChar === null)
sequenceChar = cells[i].innerHTML;
// Otherwise, confirm that this cell holds
// the same character(s) as the previous cell(s).
else if (cells[i].innerHTML !== sequenceChar)
return false;
}
// If we reached this point, the entire sequence
// of cells hold the same character(s).
return true;
}
};

Javascript Tooltip Not Working in IE

Hello guys on my blog I use this script:
jQuery(document).ready(function () {
jQuery(".postbox").hover(function () {
tipinfo = $(this).find('.tipinfo');
var t = jQuery(this).position() + jQuery(this).width();
var leftto = t.left + jQuery(this).width() - 30;
tipinfo.css({
top: jQuery(this).position().top + jQuery(this).height() - 2,
left: leftto
});
tipinfo.show(); //vedi tooltip
}, function () {
tipinfo.hide(); //nascondi tooltip
})
});
The tooltip works perfectly with all browsers except IE. I know that the state Hover the browser from Microsoft is not working, so I ask for your help. There is a hack to remedy the problem?
I would be very grateful for your help
The CSS:
.tipinfo {
border-radius: 3px 3px 3px 3px;
color: #FFFFFF;
display: none;
position: absolute;
width: 350px;
z-index: 1000;
}
.bgbull {
background: url(images/bgbulle.png) no-repeat scroll 0 0 transparent;
height: 29px;
line-height: 35px;
padding-left: 50px;
width: 308px;
}
.infob {
background: none repeat scroll 0 0 #151515;
border-bottom: 1px solid #151515;
border-left: 1px solid #151515;
border-right: 1px solid #151515;
line-height:1.2em;
padding: 5px
;width: 296px;
}
.bgbullbottom {
background: url(images/bgbullebottom.png) no-repeat scroll 0 0 transparent;
height: 29px;
line-height: 35px;
padding-left: 50px;
width: 308px;
}
HTML Code:
<div class="tipinfo" style="display:none;">
<div class="bgbull"></div>
<div class="infob">
<h4 style="color:#494949;font-family:arial,sans-serif;font-size:12px;font-weight:bold;"><?php the_title_attribute(); ?></h4>
<br>
<span style="color:#bbb;"><?php the_excerpt(); ?></span>
<br>
<div style="margin-top:2px;border-top:1px dotted #323232;"></div><br>
<div style="color:#bbb;">
<span class="info">Genere: </span><br />
<span class="info">Durata: </span><br />
<span class="info">Non sai se ti piace? </span>
</div>
<div class="clear"></div>
</div>
<div class="bgbullbottom"></div>
</div>
This like looks wrong to me:
var t = jQuery(this).position() + jQuery(this).width();
Because jQuery(this).position() returns object, but jQuery(this).width() returns integer. Probably you should change it to :
var t = jQuery(this).position();
t.left += jQuery(this).width();
As far as I know you need to add the hover behaviour to IE<8. I don't know if jquery adds this functionality back, include the following line in your CSS:
body {/* ...*/behavior:url("/styles/csshover.htc");}
And the following in csshover.htc (copied with original credit, can find it on the listed page anymore)
<attach event="ondocumentready" handler="parseStylesheets" />
<script language="JScript">
/**
* Pseudos - V1.30.050121 - hover & active
* ---------------------------------------------
* Peterned - http://www.xs4all.nl/~peterned/
* (c) 2005 - Peter Nederlof
*
* Credits - Arnoud Berendsen
* - Martin Reurings
* - Robert Hanson
*
* howto: body { behavior:url("csshover.htc"); }
* ---------------------------------------------
*/
var currentSheet, doc = window.document, activators = {
onhover:{on:'onmouseover', off:'onmouseout'},
onactive:{on:'onmousedown', off:'onmouseup'}
}
function parseStylesheets() {
var sheets = doc.styleSheets, l = sheets.length;
for(var i=0; i<l; i++)
parseStylesheet(sheets[i]);
}
function parseStylesheet(sheet) {
if(sheet.imports) {
try {
var imports = sheet.imports, l = imports.length;
for(var i=0; i<l; i++) parseStylesheet(sheet.imports[i]);
} catch(securityException){}
}
try {
var rules = (currentSheet = sheet).rules, l = rules.length;
for(var j=0; j<l; j++) parseCSSRule(rules[j]);
} catch(securityException){}
}
function parseCSSRule(rule) {
var select = rule.selectorText, style = rule.style.cssText;
if(!(/(^|\s)(([^a]([^ ]+)?)|(a([^#.][^ ]+)+)):(hover|active)/i).test(select) || !style) return;
var pseudo = select.replace(/[^:]+:([a-z-]+).*/i, 'on$1');
var newSelect = select.replace(/(\.([a-z0-9_-]+):[a-z]+)|(:[a-z]+)/gi, '.$2' + pseudo);
var className = (/\.([a-z0-9_-]*on(hover|active))/i).exec(newSelect)[1];
var affected = select.replace(/:hover.*$/, '');
var elements = getElementsBySelect(affected);
currentSheet.addRule(newSelect, style);
for(var i=0; i<elements.length; i++)
new HoverElement(elements[i], className, activators[pseudo]);
}
function HoverElement(node, className, events) {
if(!node.hovers) node.hovers = {};
if(node.hovers[className]) return;
node.hovers[className] = true;
node.attachEvent(events.on,
function() { node.className += ' ' + className; });
node.attachEvent(events.off,
function() { node.className =
node.className.replace(new RegExp('\\s+'+className, 'g'),''); });
}
function getElementsBySelect(rule) {
var parts, nodes = [doc];
parts = rule.split(' ');
for(var i=0; i<parts.length; i++) {
nodes = getSelectedNodes(parts[i], nodes);
} return nodes;
}
function getSelectedNodes(select, elements) {
var result, node, nodes = [];
var classname = (/\.([a-z0-9_-]+)/i).exec(select);
var identify = (/\#([a-z0-9_-]+)/i).exec(select);
var tagName = select.replace(/(\.|\#|\:)[a-z0-9_-]+/i, '');
for(var i=0; i<elements.length; i++) {
result = tagName? elements[i].all.tags(tagName):elements[i].all;
for(var j=0; j<result.length; j++) {
node = result[j];
if((identify && node.id != identify[1]) || (classname && !(new RegExp('\\b' +
classname[1] + '\\b').exec(node.className)))) continue;
nodes[nodes.length] = node;
}
} return nodes;
}
</script>

Categories