Why do I have to click twice to get links in search results menu to load page? - javascript

QUESTION:
Why do I have to click twice to get links in search results menu to load page?
See here:
Type in Staff, or Blog in the filter field. You have to click on each link twice to get the page to load?
https://startech-enterprises.github.io/docs/data-integration-and-etl/branches-and-loops-local.html
I'm trying to get to this behaviour (i/e just one click):
https://learn.microsoft.com/en-us/dotnet/csharp/linq/
NOTE
The code in the link above has now been updated, based on the answers given below
CODE
JS I'm using
/**
* Search Filter
*/
"use strict";
(function searchFilter() {
eventListeners();
// Add Event Listerns
function eventListeners(){
document.getElementById('searchFilter').addEventListener('keyup', searchQuery);
document.getElementById('searchFilter').addEventListener('focusout', searchQuery);
document.getElementById('searchFilter').addEventListener('focusin', searchQuery);
};
function searchQuery(){
// Declare variables
let input, filter, ul_toc, li_toc, ul_suggestions, li_suggestion, a1, a2, a3, i, j, k, txtValue, txtValue2, txtValue3, link;
input = document.getElementById('searchFilter');
filter = input.value.toUpperCase();
ul_toc = document.getElementsByClassName("toc")[0];
li_toc = ul_toc.getElementsByClassName("none");
ul_suggestions = document.getElementsByClassName("searchFilter-suggestions")[0];
// Check whether input is empty. If so hide UL Element
if (filter === "") {
ul_suggestions.classList.add("is-hidden")
};
// Check whether input is not empty. If so show UL Element
if (filter !== "") {
ul_suggestions.classList.remove("is-hidden")
};
// Check whether input is not active. If so hide UL Element
if (input !== document.activeElement) {
setTimeout(function(){
ul_suggestions.classList.add("is-hidden");
}, 2000);
};
// Check whether input is active. If so show UL Element
if (input === document.activeElement) {
ul_suggestions.classList.remove("is-hidden")
};
// Keep emptying UL on each keyup event, or when input element is not active
ul_suggestions.innerHTML = "";
let df = new DocumentFragment();
// Run search query so long as filter is not an empty string
if(filter !== ""){
// Loop through all list items, and update document fragment for those that match the search query
for (i = 0; i < li_toc.length; i++) {
a1 = li_toc[i].getElementsByTagName("a")[0];
txtValue = a1.textContent || a1.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
// Start creating internal HTML
li_suggestion = document.createElement('li');
li_suggestion.classList.add("searchFilter-suggestion");
// Parent span element
let span = document.createElement("SPAN");
span.className = ("is-block is-size-7 has-padding-left-small has-padding-right-small");
link = document.createElement('a');
link.href = a1.href;
span.appendChild(link);
// Child 1 span element
let span2 = document.createElement("SPAN");
span2.className = ("is-block has-overflow-ellipsis-tablet");
span2.textContent = txtValue;
// Child 2 span element
let span3 = document.createElement("SPAN");
span3.className = ("is-block has-text-subtle has-overflow-ellipsis is-size-8 has-line-height-reset has-padding-bottom-extra-small");
j = 0;
let immediateParent = li_toc[i].parentElement;
let correctParent = li_toc[i].parentElement;
// Get top most level of branch --> Set as Node 1
while(true){
if (immediateParent.parentElement.classList.contains('toc')) break;
immediateParent = immediateParent.parentElement;
j++;
};
if (j == 0){
a2 = li_toc[i].getElementsByTagName("a")[0];
}
else {
k = 0;
for ( k = 0; k < j - 1; k++) {
correctParent = correctParent.parentElement;
};
a2 = previousByClass(correctParent, "treeitem");
a2 = child_by_selector(a2, "tree-expander")
}
txtValue2 = a2.textContent || a2.innerText;
txtValue2 = document.createTextNode(txtValue2);
// Insert Chevron Right --> Set as Node 2
let span4 = document.createElement("SPAN");
span4.className = ("has-padding-right-extra-small has-padding-left-extra-small");
span4.innerHTML = '&nbsp&#9002&nbsp';
span4.setAttribute("style", "font-size: 0.70rem; font-weight: bold");
// Get second-top most level of branch --> Set as Node 3
correctParent = li_toc[i].parentElement;
switch (j) {
case 0:
a3 = "";
break;
case 1:
a3 = li_toc[i].getElementsByTagName("a")[0];
default: {
k = 0;
for ( k = 0; k < j - 2; k++) {
correctParent = correctParent.parentElement;
};
a3 = previousByClass(correctParent, "treeitem");
a3 = child_by_selector(a3, "tree-expander")
}
}
if (a3 != ""){
txtValue3 = a3.textContent || a3.innerText;
txtValue3 = document.createTextNode(txtValue3);
span3.appendChild(txtValue2);
span3.appendChild(span4);
span3.appendChild(txtValue3);
} else {
span3.appendChild(txtValue2);
}
span.firstChild.appendChild(span2);
span.firstChild.appendChild(span3);
li_suggestion.appendChild(span);
df.appendChild(li_suggestion)
}
}
// Output HTML, and remove is-hidden class
ul_suggestions.appendChild(df);
}
}
})();
// WAIT TILL DOCUMENT HAS LOADED BEFORE INITIATING FUNCTIONS
document.addEventListener('DOMContentLoaded', searchFilter);
CSS I'm using:
/* Search Filter */
.filter-icon{
display: inline-block;
height:0.9rem;
width: 1.0rem;
text-transform: none;
text-align: center;
}
.searchFilter {
display: inline-block;
position: relative;
}
.searchFilter-input {
padding-right: 26px;
}
.searchFilter-suggestions {
list-style-type: none;
z-index: 1;
position: absolute;
max-height: 18rem;
min-width: 100%;
max-width: 100%;
padding: 0;
margin: 2px 0 0 !important;
cursor: default;
box-shadow: 0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 .3px .9px 0 rgba(0,0,0,0.108);
border: 1px solid #e3e3e3;
background-color: white;
}
#media screen and (min-width: 768px), print {
.searchFilter-suggestions {
max-width: 500px;
}
}
.searchFilter-suggestion {
display: block;
border: 1px solid transparent;
}
.searchFilter-suggestion a {
color: rgb(23, 23, 22);
text-decoration: none;
}
.searchFilter-suggestion:hover{
background-color: #f2f2f2;;
border: 1px solid rgba(0,0,0,0);
}
.is-hidden {
display: none !important;
}
Relevant portion of HTML with UL that loads the search results:
(The search results document fragment generated by the JS gets loaded in the ul, with the class, searchFilter-suggestions)
form class = "has-margin-bottom-small" action="javascript:" role="search">
<label class="visually-hidden">Search</label>
<div class="searchFilter is-block">
<div class="control has-icons-left">
<input id="searchFilter" class="searchFilter-input input control has-icons-left is-full-width is-small" role="combobox" maxlength="100" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" placeholder="Filter by title" type="text">
<span class="icon is-small is-left">
<img src="/../docs/assets/images/filter.png" class="filter-icon">
</span>
</div>
<ul class="searchFilter-suggestions is-vertically-scrollable is-hidden"></ul>
</div>
</form>

I think the best solution is to remove the focus listeners temporarily.
It should work using this:
(function searchFilter() {
let input = document.getElementById('searchFilter');
let suggestions = document.getElementsByClassName("searchFilter-suggestions")[0];
eventListeners();
// Add Event Listerns
function eventListeners() {
input.addEventListener('keyup', searchQuery);
suggestions.addEventListener("mouseenter", () => removeInputFocusListeners());
suggestions.addEventListener("mouseleave", () => addInputFocusListeners());
};
function addInputFocusListeners() {
input.addEventListener('focusout', searchQuery);
input.addEventListener('focusin', searchQuery);
}
function removeInputFocusListeners() {
input.removeEventListener('focusout', searchQuery);
input.removeEventListener('focusin', searchQuery);
}
...

Related

how to remove the quotes or get element from this (javascript)

As topic, how can I remove the quote in the picuture below or get the img element from this?
(https://i.stack.imgur.com/kdPAP.png)
I m new to javascript and start making an image slider that can pop up a window while clicked to the image.
I cloned the li object which is clicked, and try to open it in the new window, it do work but how can I get the img only without the li?
Right now i m trying to call the cloned this object with innerHTML, but it shows the img element with quote, is there any way to remove the quote?
the quote that i want to remove
first time ask a question in here, if i violate any rules in the post, i delete the post, sorry for causing any inconvenience.
Here is the code
<!DOCTYPE html>
<html>
<head>
<style>
.risuto1 {
max-width: 480px;
max-height: 270px;
margin: auto;
position: relative;
}
ul {
list-style-type: none;
margin: auto;
padding: 0;
}
.aitemu>img {
max-width: 100%;
}
.aitemu {
display: none;
position: relative;
}
.aitemu.akutibu {
display: block;
}
.risuto1>.mae,
.tsugi {
width: auto;
height: auto;
padding: 20px;
top: 102.6px;
position: absolute;
cursor: pointer;
background-color: red;
}
.risuto1>.tsugi {
left: 431.8px;
}
</style>
</head>
<body>
<script>
var risuto1 = document.createElement("div");
risuto1.classList.add("risuto1");
document.body.appendChild(risuto1);
var suraidaaitemu = document.createElement("ul");
suraidaaitemu.classList.add("suraidaaitemu");
risuto1.appendChild(suraidaaitemu);
var imejisosurisuto = ["https://pbs.twimg.com/media/CGGc3wKVEAAjmWj?format=jpg&name=medium", "https://pbs.twimg.com/media/EYCXvuzU8AEepqD?format=jpg&name=large", "https://s3-ap-northeast-1.amazonaws.com/cdn.bibi-star.jp/production/imgs/images/000/668/074/original.jpg?1626914998", "https://livedoor.blogimg.jp/rin20064/imgs/7/3/73251146.jpg", "https://www.tbs.co.jp/anime/oregairu/character/img/chara_img_02.jpg"]
//var imejirisuto=[]
for (var n = 0; n < imejisosurisuto.length; n++) {
var imeji = document.createElement("img");
imeji.src = imejisosurisuto[n];
var aitemu = document.createElement("li");
aitemu.classList.add("aitemu");
suraidaaitemu.appendChild(aitemu);
aitemu.appendChild(imeji);
aitemu.onclick=atarashivindou;
}
var akutibunasaishonoko = document.querySelector(".suraidaaitemu").firstChild;
akutibunasaishonoko.classList.add("akutibu");
var mae = document.createElement("div");
mae.classList.add("mae");
mae.innerHTML = "&#10094";
risuto1.appendChild(mae);
var tsugi = document.createElement("div");
tsugi.classList.add("tsugi");
tsugi.innerHTML = "&#10095";
risuto1.appendChild(tsugi);
var tensuu = 0;
var suraido = document.querySelector(".suraidaaitemu").children;
var gokeisuraido = suraido.length;
tsugi.onclick = function () {
Tsugi("Tsugi");
}
mae.onclick = function () {
Tsugi("Mae");
}
function Tsugi(houkou) {
if (houkou == "Tsugi") {
tensuu++;
if (tensuu == gokeisuraido) {
tensuu = 0;
}
}
else {
if (tensuu == 0) {
tensuu = gokeisuraido - 1;
}
else {
tensuu--;
}
}
for (var i = 0; i < suraido.length; i++) {
suraido[i].classList.remove("akutibu");
}
suraido[tensuu].classList.add("akutibu");
}
function atarashivindou(){
var Atarashivindou = window.open("", "_blank", "width: 1000px, max-height: 562.5px");
var kakudaigazou=document.createElement("div");
kakudaigazou.classList.add("kakudaigazou");
Atarashivindou.document.body.appendChild(kakudaigazou);
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
}
</script>
</body>
.innerHTML is a string. You don't want to append a string, but the element. So change this:
var koronaitemu=this.cloneNode(true);
var koronimeji=koronaitemu.innerHTML;
kakudaigazou.append(koronimeji);
...to this:
var koronimeji=this.querySelector("img").cloneNode();
kakudaigazou.append(koronimeji);

repeat putting input element randomly between user's text

I have a text element that is built when the user clicks a button. In the middle of that text, I added an input element.I want to make this process repeats seven times but it looks complicated. I actually made a lot of things but here are the important ones So, First I made an input element and a button when the user enter input and click the button what he wrote will be displayed in a h1 element with a random missing word Then,I made an input element in the that the missing word should've been in.What I want is that this to repeat this process seven times.
function myFunction() {
var x = document.getElementById("input").value;
x = x + " ";
var y = document.getElementById("inputed");
var a,b = "c";
const c=[];
const d=[];
var e;
var f = 0;
const array = [];
const z = x.length;
for (let index = 0; index < 7; index++) {
a= "c";
b= "c";
c.push(0);
d.push(0);
c[index] = 0;
d[index] = 0;
e = 1;
f = 0;
//Here the program will get a random space location and the space after it
while (a != " ") {
c[index] = Math.floor(Math.random() * x.length - 2);
a = x.charAt(c[index]);
}
d[index] = c[index];
//The variable d will be the same as c and will increase until its value corrspends to a space
while (b != " ") {
d[index]++;
b = x.charAt(d[index]);
}
//I want the y.innerHTML to write from the 0 to c[0] then display the input element then from d[0] //to c[1] and display the input element again and form d[1] to c[2] until 7
y.innerHTML = `${x.slice(
0,
c[0]
)}<input type="text" style="color: gray;border:2px solid;border-radius: 10px;outline: none;
font-size: x-large;height:40px;width: 100px;" >${x.slice(d[0], z)} `;
}
}
I had problems understanding perfectly your code so I couldn't answer trying to address the exact problems affecting your specific algorithm.
Anyway I made an attempt trying to understand your description and as far as I could get I tried to implement a demo beginning from a input text filled by the user and:
When the button PARSE SENTENCE gets clicked, the procedures parses the
input text splitting its content by white spaces to find out the
words.
Then it determines how many random words he wants to "remove" from
the string and at which index.
Then it creates a span element for each of those words and put all of them
in a separate array
Such spans, will have the word in their innerText, the default class
word and an added class that will be kept-word if that's a word not
to remove and removed-word otherwise. Plus they will keep track of that original word inside a data attribute called data-original
Those spans get appended to the #transformed element, and at this
stage, if the word belongs to the class .removed-word its
innerText gets emptied and its contenteditable attribute
activated.
In the end, after the parsing of the sentence, the exact spans code
will be shown in the <pre> element to give evidence of what's going
on
I know it's very far from what you have asked.. considering I didn't strictly stressed the algorithm aspect and mostly used shortcut like split, includes, contains and more importantly I totally changed your logics and used spans for words parsed and didn't use the input at all but contenteditable.
I sincerely hope it will anyway give some inspiration
function transform(){
const input = document.getElementById('input').value.trim();
const words = input.split(" ");
const nrOfWordsToReplace = Math.floor(Math.random() * words.length);
const indexesOfWordsToReplace
= Array.from({length: nrOfWordsToReplace}, () => {
return Math.floor(Math.random() * words.length);
});
//for each word in the input, create a span element to add in #transformed
//words expected to be kept will have their span with class .word.kept-word
//words expected to be removed will have their span with class .word.remove-word
let index = 0;
const outputWords = [];
for(word of words){
if( indexesOfWordsToReplace.includes(index) ){
const outputWord = createOutputWordElement(word, 'removed-word');
outputWords.push( outputWord );
}else{
const outputWord = createOutputWordElement(word, 'kept-word');
outputWords.push( outputWord );
}
index++;
}
const codeContainer = document.querySelector('pre');
codeContainer.innerHTML = '';
//clear its content appends those spans to #transform
const transformed = document.getElementById('transformed');
transformed.innerHTML = '';
for(outputWord of outputWords){
if (outputWord.classList.contains('removed-word')){
outputWord.innerText = '';
outputWord.contentEditable = true;
}
transformed.append(outputWord);
const code = document.createElement('code');
code.innerText = outputWord.outerHTML;
codeContainer.append(code);
}
}
//returns a span element having the word as content and classname among its classes
function createOutputWordElement(word, classname){
const outputWord = document.createElement('span');
outputWord.classList.add('word');
outputWord.classList.add(classname);
outputWord.dataset.original = word;
outputWord.innerText = word;
return outputWord;
}
body{
padding: 1rem;
}
*{
box-sizing: border-box;
}
button{
width: 100%;
margin-top: 1rem;
margin-bottom: 1rem;
padding: 1rem;
cursor: pointer;
text-transform: uppercase;
}
#input{
display: block;
width: 100%;
}
pre code{
display: block;
}
#transformed{
border: dashed 3px darkgray;
padding: 1rem;
}
.word{
border: solid 2px;
padding: .25rem;
margin-right: .50rem;
display: inline-block;
}
.word.kept-word{
border-color: darkgray;
}
.word.removed-word{
border-color: red;
cursor: pointer;
min-width: 2rem;
}
.
<input type="text" id="input">
<button type="button" onclick="transform();">Parse sentence</button>
<div id="transformed"></div>
<pre>
</pre>

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

How to Change JQuery Value Through <Input> Dynamically?

The following fiddle converts texts into paragraphs and the problem is the JQuery function attribute chunkSize = 100; currently defines the amount of characters for each divided paragraph to contain.
Is it possible for the user to be able to change this dynamically through the use of an <input> and <button> where the user would be able to type their desired characters for each dynamic paragraph and apply it?
Fiddle
If a new fiddle could please be provided, it would be very 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() {
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;" placeholder="Custom Characters per box">
<button>
Go
</button>
<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>
Give an id for your input.
<input id="custom" placeholder="Custom Characters per box" style="width:200px;">
Add below code into initialDistribute function.
custom = parseInt(document.getElementById("custom").value); //Get value of the input.
chunkSize = (custom>0)?custom:100; //If Custom value is more than `0`, take that as `chunkSize` value else `100`
See Fiddle
You can use input type="number" element, button element; set chunkSize to input type="number" valueAsNumber property at click of button
html
<label>chunkSize:<input class="chunkSize" type="number" /></label>
<button class="chunkSize">
Set chunkSize
</button>
javascript
$("button.chunkSize").click(function(e) {
var _chunkSize = $("input.chunkSize")[0].valueAsNumber;
chunkSize = _chunkSize;
})
jsfiddle https://jsfiddle.net/csz0ggsw/11/

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