Javascript function .show() not using HTML code - on Page Search - javascript

I found some Javascript code that does exactly what I want it to do. It searches a page of <li> for text that you enter in a search box.
However, It does not show (or use) the HTML markup that is within the text.
$(document).ready(function() {
/* initially hide product list items */
$("#dino-list li").hide();
/* highlight matches text */
var highlight = function(string) {
$("#dino-list li.match").each(function() {
var matchStart = $(this).text().toLowerCase().indexOf("" + string.toLowerCase() + "");
var matchEnd = matchStart + string.length - 1;
var beforeMatch = $(this).text().slice(0, matchStart);
var matchText = $(this).text().slice(matchStart, matchEnd + 1);
var afterMatch = $(this).text().slice(matchEnd + 1);
$(this).html(beforeMatch + "<em>" + matchText + "</em>" + afterMatch);
});
};
/* filter products */
$("#search-dinosaurs").on("keyup click input", function() {
if (this.value.length > 0) {
$("#dino-list li").removeClass("match").hide().filter(function() {
return $(this).text().toLowerCase().indexOf($("#search-dinosaurs").val().toLowerCase()) != -1;
}).addClass("match").show();
highlight(this.value);
$("#dino-list").show();
} else {
$("#dino-list, #dino-list li").removeClass("match").hide();
}
});
});
input[type=text] {
width: 200px;
padding: 8px 10px;
}
li em {
background: #ff6;
font-weight: bold;
font-style: normal;
}
<input type="text" id="search-dinosaurs" placeholder="Search for Dinosaurs (start typing)" />
<ul id="dino-list">
<li>Diplo<BR>docus</li>
<li>Stego<FONT COLOR="RED">saurus</FONT>
</li>
<li>Triceratops</li>
<li>Pteradactyl</li>
<li>Tyrannosaurus Rex</li>
<li>Protoceratops</li>
<li>Iguanadon</li>
<li>Velociraptor</li>
</ul>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
In the search box, type: Dipl
You will see the full name, and the <BR> is ignored.
How can I get this code to use the HTML code that is inline with the result?
the result should show:
Diplodocus
Thanks for any thoughts

try this one
$(function(){
$('#dino-list>li').hide();
$('#search-dinosaurs').on('keyup',function(){search(this.value)})
})
function search(txt){
var target = $('#dino-list');
// reset content
var content = target.html();
if (typeof target.data('content')!='undefined') {
target.html(target.data('content'));
} else target.data('content',content);
$('#dino-list>li').hide();
if (txt!='') {
// begin search
$('#dino-list').find('*').contents().each(function() {
if (this.nodeType === 3) {
// wrap text node with 'em'
$(this).replaceWith(this.nodeValue.replace(new RegExp('('+txt+')','gi'),'<em>$1</em>'))
};
});
// display li with em
$('em',target).each(function(){
$(this).closest('li').show();
})
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="search-dinosaurs" placeholder="Search for Dinosaurs (start typing)" />
<ul id="dino-list">
<li>Diplo<BR>docus</li>
<li>Stego<FONT COLOR="RED">saurus</FONT></li>
<li>Triceratops</li>
<li>Pteradactyl</li>
<li>Tyrannosaurus Rex</li>
<li>Protoceratops</li>
<li>Iguanadon</li>
<li>Velociraptor</li>
</ul>

Related

How to prevent centered text in input button be moved when dynamically changed

I have an input button with a centered text. Text length is changing dynamically with a js (dots animation), that causes text moving inside the button.
Strict aligning with padding doesn't suit because the text in the button will be used in different languages and will have different lenghts. Need some versatile solution. The main text should be centered and the dots should be aligned left to the end of the main text.
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
var dot = '.';
if(dots < 3) {
$('#payDots').val('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').val('processing');
dots = 0;
}
}
<input id="payDots" type="button" value="Pay" class="button">
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
https://jsfiddle.net/v8g4rfsw/1/ (button should be pressed)
The easiest as this is a value and extra elements can't be inserted, would be to just use leading spaces to make the text appear as it's always centered.
This uses the plugin I wrote for your previous question
$.fn.dots = function(time, dots) {
return this.each(function(i,el) {
clearInterval( $(el).data('dots') );
if ( time !== 0 ) {
var d = 0;
$(el).data('dots', setInterval(function() {
$(el).val(function(_,v) {
if (d < dots) {
d++;
return ' ' + v + '.';
} else {
d = 0;
return v.substring(dots, v.length - dots)
}
})
}, time));
}
});
}
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).val('Proccessing').prop('disabled',true).dots(600, 3);
});
});
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="payDots" type="button" value="Pay" class="button">
You can find updated code below
Click Here
HTML Code
<button id="payDots">
<span>Pay</span>
</button>
JS Code
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
$('button').css('padding-left','100px','important');
var dot = '.';
if(dots < 3) {
$('#payDots').text('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').text('processing');
dots = 0;
}
}
CSS Code
button{
text-align: left;
width: 300px;
font-size: 20px;
position:relative;
padding-left:130px;
}

OnKeyup search string and hide/show - jQuery

I'm trying to filter a list of span tags on keyup.
I've created something only it returns strange values...
https://jsfiddle.net/5u373deu/1/
function searchClients() {
var clientSearch = document.getElementById("clientSearch");
var s = clientSearch.value;
$('.select-options span:not(:contains("' + s + '"))').hide();
}
$("#clientSearch").keyup(function() {
searchClients();
});
To make it become case sensitive, you need to override your current contains
jQuery.expr[':'].contains = function(a, index, obj) {
return jQuery(a).text().toUpperCase()
.indexOf(obj[3].toUpperCase()) >= 0;
};
function searchClients() {
var clientSearch = document.getElementById("clientSearch");
var s = clientSearch.value;
$('.select-options span').show();
$('.select-options span:not(:contains("' + s + '"))').hide();
}
$("#clientSearch").keyup(function() {
searchClients();
});
span {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-options ps-container below ps-active-y">
<input id="clientSearch" type="text">
<span>Bitcoin</span><span>Cat</span><span>Whiskey</span><span>Table</span>
Try refreshing your display everytime :
Note that your search is case sensitive.
function searchClients() {
var clientSearch = document.getElementById("clientSearch");
var s = clientSearch.value;
$('.select-options span').show();
$('.select-options span:not(:contains("' + s + '"))').hide();
}
$("#clientSearch").keyup(function() {
searchClients();
});
span {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-options ps-container below ps-active-y">
<input id="clientSearch" type="text">
<span>Bitcoin</span><span>Cat</span><span>Whiskey</span><span>Table</span>
Here you go: https://jsfiddle.net/5u373deu/6/
The problem was with the fact that you were not showing all elements when the user cleared the filter text.
function searchClients() {
var clientSearch = document.getElementById("clientSearch");
var s = clientSearch.value;
$('.select-options span').show();
$('.select-options span:not(:contains("'+s+'"))').hide();
}
$("#clientSearch").keyup(function() {
searchClients();
});

How can I make `.innerText` ignore invisible children of an invisible element?

Result of the test code below:
div[0].innerText === "aaaaa zzzzz"
div[1].innerText === "␤aaaaa␤invisible␤zzzzz␤"
How can I force innerText to give the same result for div[1] as it gives for div[0]?
I’ve tried to append div[1] to a temporary document but, since the document wasn’t actually displayed, it didn’t help. Only appending it to a literally visible document works.
Test code
var div = [];
div[0] = document.getElementById("visible");
div[1] = div[0].cloneNode(true);
show(0);
show(1);
function show(i) {
document.getElementById("output").innerHTML +=
"<p>div[" + i + "].innerText === <code>" +
div[i].innerText.replace(/\n/g, "␤") + "</code></p>";
}
#visible {display: block; font-family: sans-serif; font-size: larger; color: red;}
code {background-color: lightgray; padding: 0 .318em;}
<div id="visible">
<span style="display: inline">aaaaa</span>
<span style="display: none">invisible</span>
<span style="display: inline">zzzzz</span>
</div>
<div id="output"></p>
Only appending it to a document literally visible to the user works.
But the user doesn't necessarily have to see that. :-) If you append it, grab innerText, and then remove it, the user will never see it:
var div = [];
div[0] = document.getElementById("visible");
div[1] = div[0].cloneNode(true);
show(0);
document.body.appendChild(div[1]); // *****
show(1);
document.body.removeChild(div[1]); // *****
function show(i) {
document.getElementById("output").innerHTML +=
"<p>div[" + i + "].innerText === <code>" +
div[i].innerText.replace(/\n/g, "␤") + "</code></p>";
}
#visible {display: block; font-family: sans-serif; font-size: larger; color: red;}
code {background-color: lightgray; padding: 0 .318em;}
<div id="visible">
<span style="display: inline">aaaaa</span>
<span style="display: none">invisible</span>
<span style="display: inline">zzzzz</span>
</div>
<div id="output"></p>
Alternately, since the element isn't in the DOM, it can't be made invisible by CSS, only inline styles. I can't think of any other inline style that would make the text get left out of innerText other than your display: none and visibility: hidden (opacity: 0, for instance, doesn't do it), so it's trivial to exclude those and normalize whitespace for non-pre elements:
function getInnerText(element) {
var node, text = "";
if (element.style.display.toLowerCase() !== "none" && element.style.visibility.toLowerCase() !== "hidden") {
for (node = element.firstChild; node; node = node.nextSibling) {
if (node.nodeType === 3) {
text += node.nodeValue;
} else if (node.nodeType === 1) {
text += getInnerText(node);
}
}
}
// Normalize all whitespace if not "pre"
if (element.tagName !== "PRE" && element.style.whiteSpace.toLowerCase().indexOf("pre") == -1) {
text = text.replace(/\s+/g, ' ');
}
return text;
}
That may well need tweaking (I don't think it handles <div>stuff<pre>big gap</pre></div> properly), but you can run with the idea if you don't want to use the first solution above...
Example:
var div = [];
div[0] = document.getElementById("visible");
div[1] = div[0].cloneNode(true);
show(0);
document.body.appendChild(div[1]); // *****
show(1);
document.body.removeChild(div[1]); // *****
function show(i) {
document.getElementById("output").innerHTML +=
"<p>div[" + i + "].innerText === <code>" +
getInnerText(div[i]).replace(/\n/g, "␤") + "</code></p>";
}
function getInnerText(element) {
var node, text = "";
if (element.style.display.toLowerCase() !== "none" && element.style.visibility.toLowerCase() !== "hidden") {
for (node = element.firstChild; node; node = node.nextSibling) {
if (node.nodeType === 3) {
text += node.nodeValue;
} else if (node.nodeType === 1) {
text += getInnerText(node);
}
}
}
// Normalize all whitespace if not "pre"
if (element.tagName !== "PRE" && element.style.whiteSpace.toLowerCase().indexOf("pre") == -1) {
text = text.replace(/\s+/g, " ");
}
return text;
}
#visible {display: block; font-family: sans-serif; font-size: larger; color: red;}
code {background-color: lightgray; padding: 0 .318em;}
<div id="visible">
<span style="display: inline">aaaaa</span>
<span style="display: none">invisible</span>
<span style="display: inline">zzzzz</span>
</div>
<div id="output"></p>

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/

Random number into div and then let delete divs in sequence. How?

So, i want to make game for my child. Have low experience in JS.
Scenario:
Have for example 4 square divs with blank bg. After refresh (or win) i want to:
Generate random numbers into div (1...4). And show them in them.
Then let player delete those divs by clicking on them, but in sequence how divs are numbered.
*For example after refresh divs have those numbers 2 3 1 4. So, user has to have rights to delete first div numbered 1 (2 3 _ 4) and so on.* If he clicks on 2 it get error , div stays in place, and user can try again delete right one.
It game for learning numbers. I have the begining.
Index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
</head>
<body>
<div class="grid">
<div id="Uleft"></div>
<div id="Uright"></div>
<div id="Dleft"></div>
<div id="Dright"></div>
</div>
<script>
$(".grid").children( "div" ).on("click", function(){
$(this).css("visibility", "hidden");
});
</script>
</body>
</html>
css.css
.grid {
margin: 0 auto;
width: 430px;
}
#Uleft, #Uright, #Dleft, #Dright {
border: 1px solid black;
width: 200px;
height: 200px;
margin: 5px;
}
#Uright {
float: right;
background-color: red;
}
#Uleft {
float: left;
background-color: blue;
}
#Dleft {
float: left;
background-color: green;
}
#Dright {
float: right;
background-color: yellow;
}
So, i guess i have use jQuery as well, but i dont know how to make it dynamic and different after refresh of page. Please help :)
http://jsfiddle.net/bNa8Z/
There are a few things you have to do. First you have to create a random array which you use sort and Math.random() to do then, you need insert the text in the squares. Find the min of the visible squares and then remove/alert depending if its the min value.
// sort by random
var rnd = [1,2,3,4].sort(function() {
return .5 - Math.random();
});
// map over each div in the grid
$('.grid div').each(function(ii, div) {
$(div).text(rnd[ii]); // set the text to the ii'th rnd
});
function minVisible() {
var min = 1e10; // a big number
$('.grid div').each(function(ii, div) {
// if not visible ignore
if ($(div).css('visibility') === "hidden" ){
return;
}
// if new min, store
var curFloatValue = parseFloat($(div).text());
console.log(curFloatValue);
if (curFloatValue < min) {
min = curFloatValue;
}
});
return min;
}
$(".grid").children( "div" ).on("click", function(){
var clickedFloatValue = parseFloat($(this).text());
if (clickedFloatValue == minVisible()) {
$(this).css("visibility", "hidden");
} else {
alert("sorry little tike");
}
});
Updated jsfiddle http://jsfiddle.net/bNa8Z/2/
Roughly this is what it would look like:
var selected = {};
$('.grid div').each(function(idx){
var is_done = false;
do{
var rand = Math.floor((Math.random()*4)+1);
if( selected[rand] == undefined ){
$(this).html(rand);
selected[rand] = 1;
is_done = true;
}
}while(!is_done);
});
alert("Start the game");
var clicked = [];
$('.grid').on('click', 'div.block', function(){
var num = $(this).html();
if( num == clicked.length + 1 ){
//alert(num + " is correct!");
clicked.push(num);
$(this).addClass("hide");
}else{
alert("Failed!");
}
if( clicked.length == 4 ){
alert("You Won!");
}
});
HTML:
<div class="grid">
<div class="block" id="Uleft"></div>
<div class="block" id="Uright"></div>
<div class="block" id="Dleft"></div>
<div class="block" id="Dright"></div>
</div>
Added CSS:
#Uleft, #Uright, #Dleft, #Dright {
position:absolute;
...
}
#Uright {
left:220px;
top:0px;
background-color: red;
}
#Uleft {
left:0px;
top:0px;
background-color: blue;
}
#Dleft {
left:0px;
top:220px;
background-color: green;
}
#Dright {
left:220px;
top:220px;
background-color: yellow;
}
.hide {
display: none;
}
See the working version at
JSFiddle
You will need to re-"run" the fiddle per game.
please try it. I think that It will help you.
var generated_random_number_sequesce = function(){
var number_array = [];
var number_string = '';
var is_true = true;
while(is_true){
var ran_num = Math.round(1 + Math.random()*3);
if(number_string.indexOf(ran_num) == -1 && ran_num < 5){
number_array[number_array.length] = ran_num;
number_string = number_string + ran_num;
if(number_array.length == 4){is_true = false;}
}
}
return number_array;
}
var set_number_on_divs = function(){
var number_array = generated_random_number_sequesce();
$(".grid").children().each(function(index, element){
$(this).attr('data-div_number' , number_array[index]);
});
}
set_number_on_divs()
var clicked = 0;
$(".grid").children( "div" ).on("click", function(){
clicked += 1;
var current_div_number = $(this).attr('data-div_number');
if( parseInt(current_div_number) == clicked){
$(this).css("visibility", "hidden");
} else{
clicked -= 1;
alert('error');
}
});

Categories