knockout toggle/expand the text on click of text - html

Binding data into html table using knockout. One of the column has large text 200 length.. and UI just got scroll long. So just want to show, first 20 length chars and click of, ... it should expand or collapse the text.
so just created a template below,
<script type="text/html" id="templateLongText">
<span data-bind="text: (Comments.length > 20 ? Comments.substring(0, 20) + '<a href=\'#\' data-bind=\'click: toggle(Comments)\'>...</a>' : Comments)"></span>
</script>
It does not work event, just rendering same text as above.
Edit:
How toggle the expand or collapse text(Comments value) on click of ...

You could add a custom binding for this, which you can bind to any simple (observable) string. This custom binding:
initially adds two child elements. A span for the (abbreviated) text and an anchor for toggling.
on every update (or only once if the text is not observable) sets the abbreviated text in the span and adds an onclick handler for toggling the text. The toggle anchor is hidden for texts having less than 20 characters.
ko.bindingHandlers.expandText = {
init: function(element, valueAccessor) {
element.appendChild(document.createElement('span'));
var toggle = document.createElement('a');
toggle.appendChild(document.createTextNode("..."));
toggle.href = "#";
element.appendChild(toggle);
},
update: function(element, valueAccessor) {
var text = ko.unwrap(valueAccessor());
var textElement = element.getElementsByTagName('span')[0];
var toggle = element.getElementsByTagName('a')[0];
var collapsed = true;
toggle.onclick = function() {
collapsed = !collapsed;
ko.utils.setTextContent(textElement, collapsed ? text.substr(0, 20) : text);
}
toggle.style.display = text.length > 20 ? 'inline' : 'none';
ko.utils.setTextContent(textElement, collapsed ? text.substr(0, 20) : text);
}
};
ko.applyBindings({
sample1: '1234567890123456789012345',
sample2: '123456789012345',
sample3: '123456789012345678901234567890'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="expandText: sample1"></div>
<div data-bind="expandText: sample2"></div>
<div data-bind="expandText: sample3"></div>

You can't implement html tag as a text in binding.
<script type="text/html" id="templateLongText">
<span data-bind="text: Comments.length > 20 ? Comments.substring(0, 20) : Comments"> </span>...
</script>

Related

Check if text is being entered in input using Javascript/jQuery

I am trying to hide a placeholder while the input is being used and while there's text inside the input. Here's a simplified version of the HTML for the input and placeholder:
<div id="search-placeholder"><span class="fa fa-search"></span> Search</div>
<input id="search-input" type="text" name="search" />
I tried using jQuery but it does not return the desired result:
$(document).ready(function(){
$('#search-input').focus(function(){
$('#search-placeholder').fadeOut(100);
}).focusout(function(){
$('#search-placeholder').fadeIn(100);
});
});
The placeholder will hide when the input is selected, as it should. But it will show again when the user clicks elsewhere, even while the input is not empty! The placeholder is visible on top of the input value, so I tried a different approach:
$('#search-input').change(function(){
if($('#search-input').val() = '') {
$('#search-placeholder').fadeIn(100);
}else{
$('#search-placeholder').fadeOut(100);
}
})
Unfortunately, this only works when the user clicks elsewhere. The placeholder still shows while typing and while the input is selected, again showing itself on top of the input value. How do I hide <div id="search-placeholder"> while <div id="search-input"> is not empty, or when the input is selected by clicking or tapping it (on focus)?
Maybe try to check the value of the input in the focusout event and only show the placeholder if it's empty:
$(document).ready(function(){
$('#search-input').focus(function(){
$('#search-placeholder').fadeOut(100);
}).focusout(function(){
if($('#search-input').val() === '')
{
$('#search-placeholder').fadeIn(100);
}
});
});
I think you could extract the $('#search-input') and $('#search-placeholder') elements to variables, so the code becomes a bit more readable.
You do this using javascript and jquery
jquery :-
$(document).ready(function(){
$('#search-input').focus(function() {
$('#search-placeholder').fadeOut(100);
});
$('#search-input').focusout(function() {
if($('#search-input').val() === '') {
$('#search-placeholder').fadeIn(100);
}
});
});
javascript
var searchInput = document.getElementById("search-input");
var searchPlaceholder = document.getElementById("search-placeholder");
searchInput.onfocus = function() {
searchPlaceholder.style.display = "none";
}
searchInput.onfocusout = function() {
if(this.value == "") {
searchPlaceholder.style.display = "block";
}
}
if you want to add fade-in fade-out transitions in javascript method use css transition property- transition: opacity 1s and instead of changing style.display change style.opacity to 1(show) and 0(hide)

Replacing text with jQuery only in active/focussed input-Element

I have a page where I have around 10 input-Elements. Some of them I gave the class .no-whitespace-allowed. Now I have a jQuery script running in the background with the purpose to avoid whitespaces in the very input-Elements:
$(function() {
var elements = $(".no_whitespace_allowed");
var func = function() {
if (elements.is(':focus')) elements.val(elements.val().replace(/\s/g, ''));
else elements.val(elements.val());
}
elements.keyup(func).blur(func);
});
However, it replaces the text in every input field with the result that I have the same text in all inputs. Any ideas?
$(".no_whitespace_allowed").keyup(function(){
$(this).val( $(this).val().replace(/\s/g, '') );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="no_whitespace_allowed" type="text">
Something like this ?

Toggle Text between multiple buttons

I would like to have two buttons which are basically categories. Let's name them category A and category B. The are displayed left and right. Below i would like to display some text which is dependent of the chosen category (i.e the clicked button) so that category A shows text A and category B shows text B.
This if for html. I'm working on a wordpress homepage.
I was able to install one button which toggles text (basically button 1 = Category A). But i couldn't manage to insert a second button (basically button 2 = Category B). Any ideas? Highly appreciated!
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Click the button to swap the text of the DIV element:</p>
<p><button onclick="myFunction()">Click Me</button></p>
<div id="myDIV">Hello</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.innerHTML === "Hello") {
x.innerHTML = "Swapped text!";
} else {
x.innerHTML = "Hello";
}
}
</script>
</body>
</html>
I expect to have 2 buttons which display 2 categories, the text should toggle according to which button has been clicked.
Could put the description in an attribute, then get the attributes value on click and change the html of the description. Here is a jsFiddle
<div>
<button class="js-button default-button" data-description="Category A's Description" onclick="myFunction(this)">
Category A
</button>
<button class="js-button default-button" data-description="Category B's Description" onclick="myFunction(this)">
Category B
</button>
</div>
<div id="js-description" class="description">
</div>
<script>
function myFunction(elem) {
var x = document.getElementById("js-description");
var description = elem.getAttribute('data-description');
x.innerHTML = description;
var button = document.getElementsByClassName('js-button');
for (var i = 0; i < button.length; i++) {
button[i].classList.remove('active-button');
}
elem.classList.add('active-button');
}
</script>
<style>
.default-button{
font-size:16px;
border-radius: 4px;
padding:7px 12px;
}
.active-button{
background:blue;
color:#fff;
}
.description{
margin-top:20px;
}
</style>
I don't really like all these solutions because everything is written from JS but contents probably come from database. So here is my solution :
// Native JS version
// Working Fiddle : https://jsfiddle.net/d34cbtw7/
var togglers = document.querySelectorAll('[data-toggle="tab"]');
for (var i = 0; i < togglers.length; i++) {
togglers[i].addEventListener('click', function() {
var tabs = document.querySelectorAll('.tab');
for(var j = 0; j < tabs.length; j++) {
tabs[j].classList.remove('active');
}
var $target = document.querySelector(this.getAttribute('data-target'));
$target.classList.add('active');
});
}
// jQuery version
$('body').on('click', '[data-toggle="tab"]', function(e) {
e.preventDefault();
// Select our target
var $target = $($(this).data('target'));
// Hide all tabs
$('.tab-contents .tab').removeClass('active');
// Show only $target tab
$target.addClass('active');
});
.tab-contents .tab {
display: none;
}
.tab-contents .tab.active {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-toggle="tab" data-target="#cat-A-content">
Cat A
</button>
<button data-toggle="tab" data-target="#cat-B-content">
Cat B
</button>
<div class="tab-contents">
<div class="tab active" id="cat-A-content">
My category A contents
</div>
<div class="tab" id="cat-B-content">
My category B contents
</div>
</div>
I also don't really like "onclick" attribute in HTML...
I've made a quick codepen as example.
You can achieve this by passing a parameter to the onClick function. In this example I keep track of the last button clicked, and the text it should render. If the last button clicked was the same button, the switched back to default. I hope this helps.
https://codepen.io/maffekill/pen/rbpjzw
HTML
<p>Click the button to swap the text of the DIV element:</p>
<p><button onclick="myFunction(1, 'TEXT A')">TEXT A</button></p>
<p><button onclick="myFunction(2, 'TEXT B')">TEXT B</button></p>
<div id="myDIV">Default Text</div>
JS
// Keep track of the button currently clicked
var activeBtn = null;
function myFunction(btnId, text) {
var x = document.getElementById("myDIV");
// If the last button is the same as the new one, show default text
if (activeBtn === btnId) {
x.innerHTML = "Default Text";
activeBtn = null
} else {
// Else show the text given to the text param
x.innerHTML = text;
activeBtn = btnId;
}
}
There are multiple ways to achieve this, but the easiest way I could come up with to explain this to you would be as following:
function myFunction(myEle) {
var x = document.getElementById("myDIV");
x.innerHTML = "This is category " + myEle.value;
}
<p>Click the button to swap the text of the DIV element:</p>
<p>
<button onclick="myFunction(this)" value="a">
Category A
</button>
<button onclick="myFunction(this)" value="b">
Category B
</button>
</p>
<div id="myDIV">Hello</div>
JSFiddle
No need to overcomplicate things.
Firstly you would like to send the clicked element from the caller (which in this case would be the clicked element as well, the <button> element). You could use JavaScript's thisfor this purpose.
Within your function you can name a parameter between parenthesis, so in my example above: function myFunction() contains a parameter called myEle so it will look like: function myFunction(myEle). Once the function will be triggered, the parameter called myEle will be set to the clicked element (or
JavaScript's this). You can simply access any of its attributes like value by using a dot: myEle.value.
Knowing the above, you could apply it to whatever you require your function to do (refer to my example code above).

Wordpress change functionality of TinyMCE button U (underline)

does anybody know how to change functionality of button in wordpress content textarea? There is a "u" button (underline) which makes text
<span style="text-decoration-line: underline;">text underlined</span>
what I need is change functionality of this button to put in content:
<u>text underlined</u>
Can someone help?
You can get this formatting once you define the underline format in the init method.
HTML
<form>
<textarea id='instance1'></textarea>
</form>
<button id='get'>Test</button>
<div id='previewHTML'></div>
<div id='previewFormat'></div>
JS
var textArea_id = "#instance1";
tinymce.init({
selector: textArea_id,
toolbar: "underline",
formats : {
underline : {inline : 'u', exact : true},
}
});
var button = document.getElementById('get');
button.onclick = function(){
var contentHTML = tinymce.activeEditor.getContent({format: 'html'});
document.getElementById('previewHTML').innerText = contentHTML;
document.getElementById('previewFormat').innerHTML = contentHTML;
}
See this DEMO

highlight word in div using javascript

hi i have to implement find and replace functionality in my project. in this functionality there is one find and replace button on the top of contenteditable div. when user click on this button, popup window will open and ask for the search word when specify word and press find it will find word in that div only. and if match found it will highlight that word. so anybody tell me how can i highlight word in div. its urgent so please . thank you.
<div id="test" contenteditable="true">
this is test <font class='classname'> some text test</font>
</div>
i want to high light only test word not else
You will need to search through the div to find the word and then put that word into a span, and change the background color of the span.
Edit: I just noticed that you are not using CSS, so you will need to insert a font tag to change the color.
I just stole this from Sphix, the documentation tool:
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node) {
if (node.nodeType == 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery.className.has(node.parentNode, className)) {
var span = document.createElement("span");
span.className = className;
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this)
});
}
}
return this.each(function() {
highlight(this);
});
}
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('.sidebar .this-page-menu li.highlight-link').fadeOut(300);
$('span.highlight').removeClass('highlight');
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlight');
});
}, 10);
$('<li class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></li>')
.appendTo($('.sidebar .this-page-menu'));
}
},
So, adding this to a js file in your site, any page with it that receives a highlight GET parameter will search and highlight the word in the page.
You can find a demo of the working code in:
http://sphinx.pocoo.org/intro.html?highlight=python
Note: This code needs jQuery, off course...
Its actually pretty easy using the prototype library:
<html>
<head>
<style type="text/css">
#content span {
background-color: yellow;
}
</style>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
Event.observe(window,'load',function(){
var htm = $('content').innerHTML;
$('content').innerHTML = htm.sub('my','<span>my</span>');
});
</script>
</head>
<body>
<div id="content">
This is the div containing my content.
</div>
</body>
</html>
This should get you started so you can implement the rest.
To highlight a word you have to select it somehow. One option is to surround the word with a span tag.
this is <span class="highlight">test</span> some text test
then specify CSS for the highlight class.