Page-Breaks in JQuery Mobile? - javascript

Is it possible to apply page-breaks to JQuery Mobile when printing?
The problem that is occurring is when attempting to print, dynamically generated paragraphs <p> split between the end and start of a new page and that section does not move over as one section in A4. I have also attempted to use page-break-after: always; and other css, however, this seems not to work.
The following JSFiddle converts text from a <textarea> into equal paragraphs <p>
Attached is a JSFiddle to better understand the problem.
Thank You!
<!DOCTYPE html>
<html>
<head>
<meta content="width=device-width, initial-scale=1" name="viewport">
<link href=
"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel=
"stylesheet">
<script src="https://code.jquery.com/jquery-1.11.3.min.js">
</script>
<script src=
"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
</script>
<title></title>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="header">
<h1>Page 1</h1>
</div>
<div class="ui-content" data-role="main">
<a data-transition="slide" href="#pagetwo">Go to Generated Paragraphs</a>
<div>
<h3>Paste text in the field below to divide text into
paragraphs..</h3>
<textarea id="textarea1" placeholder=
"Type text here, then press the button below." rows="5">
</textarea> <button id="go">Divide Text into Paragraphs</button>
</div>
</div>
<div data-role="footer">
<h1>Page 1 Footer</h1>
</div>
</div>
<div data-role="page" id="pagetwo">
<div data-role="header">
<h1>Page 2</h1>
</div>
<div class="ui-content" data-role="main">
<button onclick="myFunction()">Print this page</button>
<script>
function myFunction() {
window.print();
}
</script>
<h5>Click on the link to go back. <b>Note</b>: fade is
default.</h5>Go to Page One
<div id="content"></div>
</div>
<div data-role="footer">
<h1>Page 2 Footer</h1>
</div>
</div>
<script>
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.setAttribute('contenteditable', true);
para.textContent = str;
content.appendChild(para);
});
}
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;
}
</script>
<style>
p { padding: 1.2em 0.5em; margin: 1.4em 0; border: 1px dashed #aaa; }
</style>
<style>
p {
page-break-before: always;
page-break-after: always;
}
p { page-break-inside: avoid;
}
</style>
</body>
</html>

JQM uses absolutely positioned pages, which page-break-after does not allow. To solve this, add something like:
#media print{
.ui-page {
position: relative !important;
}
}
I hope this helps someone!

Related

font size change onclick for more than on div

I have 10 div and when any one click on any div and then click on increment button then font size of that div should be increase.
It is working for single div. But I need for more than one div.
When I remove getDate(), then it is working for one div.
I have to click on div and then click on increment or decrement tag.Then font size of that div should be increment or decrement.
function getDate(e) {
var originalSize = $('#' + e).css('font-size');
}
$(document).ready(function() {
//var originalSize = $('div').css('font-size');
$('#linkIncrease').click(function() {
modifyFontSize('increase');
});
$('#linkDecrease').click(function() {
modifyFontSize('decrease');
});
$('#linkReset').click(function() {
modifyFontSize('reset');
})
function modifyFontSize(flag) {
var divElement = $('#divContent');
var currentFontSize = parseInt(divElement.css('font-size'));
if (flag == 'increase')
currentFontSize += 1;
else if (flag == 'decrease')
currentFontSize -= 1;
else
currentFontSize = 16;
divElement.css('font-size', currentFontSize);
}
});
.divClass {
font-size: 12px;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<a id="linkIncrease" href="#"><b>+</b></a>
<a id="linkDecrease" href="#"><b>-</b></a>
<a id="linkReset" href="#"> <b>X</b></a>
<br /> <br />
<div id="divContent" class="divClass" onClick="getDate(this.id);"> Hello </div>
<br>
<div id="divContent1" class="divClass" onClick="getDate(this.id);"> Hello </div>
Version that increases only CLICKED div
It saves the original size on the div itself in a data attribute
I also bail out if nothing was clicked before plus or minus are clicked
let divElement;
function modifyFontSize(flag) {
let $divElement = $("#" + divElement);
if ($divElement.length === 0) console.log("Nothing selected")
let currentFontSize = parseInt($divElement.css('font-size'));
if (flag == 'increase')
currentFontSize += 1;
else if (flag == 'decrease')
currentFontSize -= 1;
else
currentFontSize = $divElement.data("orgSize") || 16;
$divElement.css('font-size', currentFontSize);
}
$(document).ready(function() {
$(".divClass").on("click", function() {
divElement = this.id;
if (!$(this).data("orgSize")) $(this).data("orgSize", $(this).css('font-size'))
})
$('#linkIncrease').click(function() {
modifyFontSize('increase');
});
$('#linkDecrease').click(function() {
modifyFontSize('decrease');
});
$('#linkReset').click(function() {
modifyFontSize('reset');
})
});
.divClass {
font-size: 12px;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<a id="linkIncrease" href="#"><b>+</b></a>
<a id="linkDecrease" href="#"><b>-</b></a>
<a id="linkReset" href="#"> <b>X</b></a>
<br /> <br />
<div id="divContent" class="divClass"> Hello </div>
<br>
<div id="divContent1" class="divClass"> Hello </div>
Try this,
let divId = '';
function getDate(e) {
var originalSize = $('#' + e).css('font-size');
divId = e;
}
$(document).ready(function() {
//var originalSize = $('div').css('font-size');
$('#linkIncrease').click(function() {
modifyFontSize('increase');
});
$('#linkDecrease').click(function() {
modifyFontSize('decrease');
});
$('#linkReset').click(function() {
modifyFontSize('reset');
})
function modifyFontSize(flag) {
var divElement = $(`#${divId}`);
var currentFontSize = parseInt(divElement.css('font-size'));
if (flag == 'increase')
currentFontSize += 1;
else if (flag == 'decrease')
currentFontSize -= 1;
else
currentFontSize = 16;
divElement.css('font-size', currentFontSize);
}
});
.divClass {
font-size: 12px;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<a id="linkIncrease" href="#"><b>+</b></a>
<a id="linkDecrease" href="#"><b>-</b></a>
<a id="linkReset" href="#"> <b>X</b></a>
<br /> <br />
<div id="divContent" class="divClass" onClick="getDate(this.id);"> Hello </div>
<br>
<div id="divContent1" class="divClass" onClick="getDate(this.id);"> Hello </div>
I added a variable 'divId' to store the selected div when the function getDate() is called. Then I apply font-sizing to that div only.

Having trouble restarting logic Tic Tac Toe game (JavaScript)

I am having trouble to look where the problem is.
I was able to create the game board and I will be implementing AI soon.
For now, I need to make it work so that everytime the game is over, it will restart a new one and resume.
However when it reaches to that point, it stops working.
From my what I've read, I may not be binding the events correctly, but I am still left puzzled.
Can anyone pinpoint what is wrong with my code?
$(document).ready(function(){
var human;
var computer;
var board = new Board()
var game;
function Human(symbol){
this.name = "Player",
this.symbol = symbol;
}
function Computer(symbol){
this.name = "Computer",
this.symbol = symbol;
}
//Modal opens when page is rendered. User can choose symbol
$("#myModal").modal()
$("#xPlayer").on('click',function(){
human = new Human("X");
computer = new Computer("O");
board.initalize();
game = new Game(human)
game.play();
})
$("#oPlayer").on('click',function(){
human = new Human("O")
computer = new Computer("X");
board.initalize();
game = new Game(computer)
game.play();
})
//Board constuctor
function Board(){
this.board = []
this.status = "";
}
//method calls for an empty board filled with "E"
Board.prototype.initalize = function(){
$("td p").empty()
this.board = ["E","E","E","E","E","E","E","E","E"]
this.status = "New Game";
}
//return true if there is a win. Otherwise, false
Board.prototype.win = function(){
var B = this.board;
//check row
for (var i = 0; i <= 6; i = i + 3){
if (B[i] !== "E" && (B[i] === B[i+1]) && (B[i+1] === B[i+2])){
board.status = "Winner is: " + game.currentPlayer.name
return true
}
}
//check column
for (var i = 0; i <= 2 ; i++ ){
if (B[i] !== "E" && (B[i] === B[i+3]) && (B[i+3] === B[i+6])){
board.status = "Winner is: " + game.currentPlayer.name
return true
}
}
//check diagonal
for(var i = 0, j = 4; i <= 2 ; i = i + 2, j = j - 2) {
if(B[i] !== "E" && (B[i] == B[i + j]) && (B[i + j] === B[i + 2 * j]) ) {
board.status = "Winner is: " + game.currentPlayer.name
return true;
}
}
return false
}
//checks if the current status is draw. If so, updates the status to "Draw"
Board.prototype.draw = function(){
//checks if the board itself is draw
for(var i = 0; i < this.board.length ; i++){
if (this.board[i] === "E"){
return false;
}
}
board.status = "Draw!"
return true;
}
//method returns array of indexes that are not empty cells in the board
Board.prototype.available = function(){
var B = this.board;
var indexes = [];
for (var i = 0; i < B.length ; i ++){
if (B[i] === "E"){
indexes.push(i)
}
}
return indexes;
}
//checks first if the User Input is valid or not
Board.prototype.validMove = function(position){
var availableCells = this.available();
return availableCells.includes(position);
}
//updates the board when using jQuery click
//it will render the webpage by prototype_writeBoard
Board.prototype.updateBoard = function(position,playerInput) {
var availableCells = this.available();
if (availableCells.includes(position)){
this.board[position] = playerInput
}
};
function Game(firstPlayer){
this.currentPlayer = firstPlayer;
this.over = false;
this.win = "";
}
Game.prototype.switchPlayer = function(){
this.currentPlayer = (this.currentPlayer === human) ? computer : human
}
Game.prototype.play = function(){
$("td").click(function(){
var position = $(this).attr("id");
var positionNumber = parseInt(position.slice(4,5))
// This here renders to the board and updates board.board
if(board.validMove(positionNumber)){
//Checks if the move is valid. If it is, append it.
//Otherwise, alert the user that it is taken
$(this).find("p").append(game.currentPlayer.symbol)
board.updateBoard(positionNumber, game.currentPlayer.symbol)
//Check if it the game is over or draw
//If either is true, play new game
if (board.win() || board.draw()){
alert(board.status)
game.restart();
}
game.switchPlayer();
}else{
alert("Already taken")
}
})
}
Game.prototype.restart = function(){
board.initalize();
game.play()
}
})
body {
background: skyblue; }
#tictactoe {
max-width: 700px;
min-height: 300px;
margin: 68px auto;
display: flex;
width: 100%; }
#tictactoe table {
width: 100%;
font-size: 65px;
text-align: center;
vertical-align: middle;
table-layout: fixed; }
td {
height: 115px;
color: #101935;
background: #F2FDFF;
border: 5px solid #DBCBD8;
border-radius: 12px;
cursor: pointer;
transition: background 0.5s ease-out, color 0.5s ease-out; }
td:hover {
background: #564787;
color: #F2FDFF; }
.modal-dialog {
text-align: center; }
.modal-dialog .modal-footer {
text-align: center; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TicTacToe FCC</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="css/styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div id="tictactoe">
<table id="game-board">
<tbody>
<tr id="row1">
<td id="cell0"><p></p></td>
<td id="cell1"><p></p></td>
<td id="cell2"><p></p></td>
</tr>
<tr id="row2">
<td id="cell3"><p></p></td>
<td id="cell4"><p></p></td>
<td id="cell5"><p></p></td>
</tr>
<tr id="row3">
<td id="cell6"><p></p></td>
<td id="cell7"><p></p></td>
<td id="cell8"><p></p></td>
</tr>
</tbody>
</table>
</div>
<!--Modal Window -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Choose your character!</h4>
</div>
<div class="modal-body">
<p>Have fun!</p>
</div>
<div class="modal-footer">
<button type="button" id="xPlayer" class="btn btn-default" data-dismiss="modal">X</button>
<button type="button" id="oPlayer" class="btn btn-default" data-dismiss="modal">O</button>
</div>
</div>
</div>
</div>
</body>
<script src="js/javascript.js" type="text/javascript"></script>
</html>
In Game.play you are binding to the onclick of the td element. Then in Game.restart you are calling Game.play which is binding to the click event again. Since you are already calling Game.play when you setup the players there is no need to call it in Game.restart since it is still bound to the click event
Game.prototype.restart = function(){
board.initalize();
/* delete-me game.play() */
}

Unable to store permanently the id of dragged item

I am working on a project in which i had to store the the 3ID's of drop item in 3 textbox. but when i dragg and drop either one it stores it's id but when i drop the second item it stores it's ID but remove the ID of first from the textbox.
code
function dropItems(idOfDraggedItem, targetId, x, y) {
var targetObj = document.getElementById(targetId);
var subDivs = targetObj.getElementsByTagName('DIV');
if(subDivs.length>0 && targetId!='body')return;
var sourceObj = document.getElementById(idOfDraggedItem);
var numericIdTarget = targetId.replace(/[^0-9]/gi,'')/1;
var numericIdSource = idOfDraggedItem.replace(/[^0-9]/gi,'')/1;
if (numericIdTarget == '101') {
document.getElementById('txt1').value = numericIdSource;
} else {
document.getElementById('txt1').value = "";
}
if (numericIdTarget == '102') {
document.getElementById('txt2').value = numericIdSource;
} else {
document.getElementById('txt2').value = "";
}
if (numericIdTarget == '103') {
document.getElementById('txt3').value = numericIdSource;
} else {
document.getElementById('txt3').value = "";
}
var fn = "Feeling1:-" + document.getElementById('txt1').value + ", Feeling2:-" + document.getElementById('txt2').value + ", Feeling3:-" + document.getElementById('txt3').value + "";
document.getElementById('txt4').value = fn;
if (numericIdTarget - numericIdSource == 100) {
sourceObj.style.backgroundColor = '';
} else {
sourceObj.style.backgroundColor = '';
}
if (targetId == 'body') {
targetObj = targetObj.getElementsByTagName('DIV')[0];
}
targetObj.appendChild(sourceObj);
}
Initialization (from comments)
$(document).ready(function(e) {
var inp1=$("#txt1");
var inp2=$("#txt2");
var inp3=$("#txt3");
$("#bttn").click(function(){
if(inp1.val()=="" && (inp2.val()!="" || inp3.val()!="")) {
alert("Provide answer in consecutive manner");
} else if((inp1.val()=="" || inp2.val()=="") && inp3.val()!="" ) {
alert("Provide answer in consecutive manner");
} else {
alert("Submit");
}
});
})
I like to use jquery's built in draggable/droppable to acquire id's maybe this will help you with your current situation.
<!DOCTYPE HTML>
<html>
<head>
<title>Test Page</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( ".draggable" ).draggable();
$( ".droppable" ).droppable({
drop: function( event, ui ) {
var id = $( this ).attr("id");
var container = ui.draggable.attr("id");
alert(id + " " + container);
}
});
});
</script>
<style>
.draggable{
width: 100px;
height: 50px;
border: 1px black solid;
margin: 0.5em;
}
.droppable{
width: 100px;
height: 50px;
border: 1px black solid;
margin: 0.5em;
}
</style>
</head>
<body>
<div id="draggable1" class="draggable">
<p>Drag me to my target</p>
</div>
<div id="draggable2" class="draggable">
<p>Drag me to my target</p>
</div>
<div id="draggable3" class="draggable">
<p>Drag me to my target</p>
</div>
<div style="height: 25px;"></div>
<div id="droppable1" class="droppable">
<p>Drop here</p>
</div>
<div id="droppable2" class="droppable">
<p>Drop here</p>
</div>
</body>
</html>

show more/Less text with just HTML and JavaScript

I am needing to create a show more/less text function, but with just JavaScript and HTML.. I can't use any additional libraries such as jQuery and it can't be done with CSS. The sample code I have added displays the 'more' text, but not the 'less'.
If someone could point me in the right direction, it would be much appreciated.
I've spent the majority of the day frying my brain over this, as its clearly not the modern way to do it, however, my HTML is:
<html>
<head>
<script type="text/javascript" src="moreless.js"></script>
</head>
<body>
Lorem ipsum dolor sit amet
<p>
<p id="textarea"><!-- This is where I want to additional text--></div>
</p>
<a onclick="showtext('text')" href="javascript:void(0);">See More</a>
<p>
Here is some more text
</body>
</html>
and my JavaScript is (moreless.js):
function showtext()
{
var text="Here is some text that I want added to the HTML file";
document.getElementById("textarea").innerHTML=text;
}
My answer is similar but different, there are a few ways to achieve toggling effect. I guess it depends on your circumstance. This may not be the best way for you in the end.
The missing piece you've been looking for is to create an if statement. This allows for you to toggle your text.
More on if statements here.
JSFiddle: http://jsfiddle.net/8u2jF/
Javascript:
var status = "less";
function toggleText()
{
var text="Here is some text that I want added to the HTML file";
if (status == "less") {
document.getElementById("textArea").innerHTML=text;
document.getElementById("toggleButton").innerText = "See Less";
status = "more";
} else if (status == "more") {
document.getElementById("textArea").innerHTML = "";
document.getElementById("toggleButton").innerText = "See More";
status = "less"
}
}
With some HTML changes, you can absolutely achieve this with CSS:
Lorem ipsum dolor sit amet
<p id="textarea">
<!-- This is where I want to additional text-->
All that delicious text is in here!
</p>
<!-- the show/hide controls inside of the following
list, for ease of selecting with CSS -->
<ul class="controls">
<li class="show">Show</li>
<li class="hide">Hide</li>
</ul>
<p>Here is some more text</p>
Coupled with the CSS:
#textarea {
display: none; /* hidden by default */
}
#textarea:target {
display: block; /* shown when a link targeting this id is clicked */
}
#textarea + ul.controls {
list-style-type: none; /* aesthetics only, adjust to taste, irrelevant to demo */
}
/* hiding the hide link when the #textarea is not targeted,
hiding the show link when it is selected: */
#textarea + ul.controls .hide,
#textarea:target + ul.controls .show {
display: none;
}
/* Showing the hide link when the #textarea is targeted,
showing the show link when it's not: */
#textarea:target + ul.controls .hide,
#textarea + ul.controls .show {
display: inline-block;
}
JS Fiddle demo.
Or, you could use a label and an input of type="checkbox":
Lorem ipsum dolor sit amet
<input id="textAreaToggle" type="checkbox" />
<p id="textarea">
<!-- This is where I want to additional text-->
All that delicious text is in here!
</p>
<label for="textAreaToggle">textarea</label>
<p>Here is some more text</p>
With the CSS:
#textarea {
/* hide by default: */
display: none;
}
/* when the checkbox is checked, show the neighbouring #textarea element: */
#textAreaToggle:checked + #textarea {
display: block;
}
/* position the checkbox off-screen: */
input[type="checkbox"] {
position: absolute;
left: -1000px;
}
/* Aesthetics only, adjust to taste: */
label {
display: block;
}
/* when the checkbox is unchecked (its default state) show the text
'Show ' in the label element: */
#textAreaToggle + #textarea + label::before {
content: 'Show ';
}
/* when the checkbox is checked 'Hide ' in the label element; the
general-sibling combinator '~' is required for a bug in Chrome: */
#textAreaToggle:checked ~ #textarea + label::before {
content: 'Hide ';
}
JS Fiddle demo.
Try to toggle height.
function toggleTextArea()
{
var limitedHeight = '40px';
var targetEle = document.getElementById("textarea");
targetEle.style.height = (targetEle.style.height === '') ? limitedHeight : '';
}
This is my pure HTML & Javascript solution:
var setHeight = function (element, height) {
if (!element) {;
return false;
}
else {
var elementHeight = parseInt(window.getComputedStyle(element, null).height, 10),
toggleButton = document.createElement('a'),
text = document.createTextNode('...Show more'),
parent = element.parentNode;
toggleButton.src = '#';
toggleButton.className = 'show-more';
toggleButton.style.float = 'right';
toggleButton.style.paddingRight = '15px';
toggleButton.appendChild(text);
parent.insertBefore(toggleButton, element.nextSibling);
element.setAttribute('data-fullheight', elementHeight);
element.style.height = height;
return toggleButton;
}
}
var toggleHeight = function (element, height) {
if (!element) {
return false;
}
else {
var full = element.getAttribute('data-fullheight'),
currentElementHeight = parseInt(element.style.height, 10);
element.style.height = full == currentElementHeight ? height : full + 'px';
}
}
var toggleText = function (element) {
if (!element) {
return false;
}
else {
var text = element.firstChild.nodeValue;
element.firstChild.nodeValue = text == '...Show more' ? '...Show less' : '...Show more';
}
}
var applyToggle = function(elementHeight){
'use strict';
return function(){
toggleHeight(this.previousElementSibling, elementHeight);
toggleText(this);
}
}
var modifyDomElements = function(className, elementHeight){
var elements = document.getElementsByClassName(className);
var toggleButtonsArray = [];
for (var index = 0, arrayLength = elements.length; index < arrayLength; index++) {
var currentElement = elements[index];
var toggleButton = setHeight(currentElement, elementHeight);
toggleButtonsArray.push(toggleButton);
}
for (var index=0, arrayLength=toggleButtonsArray.length; index<arrayLength; index++){
toggleButtonsArray[index].onclick = applyToggle(elementHeight);
}
}
You can then call modifyDomElements function to apply text shortening on all the elements that have shorten-text class name. For that you would need to specify the class name and the height that you would want your elements to be shortened to:
modifyDomElements('shorten-text','50px');
Lastly, in your your html, just set the class name on the element you would want your text to get shorten:
<div class="shorten-text">Your long text goes here...</div>
I hope this helps you. Here is the functionality:
When text characters is less than or equal to 12. Then it displays the whole text and also does not display the more/less button
When text characters is more than 12. Displays only 12 characters of the text and also a More button which when pressed, shows the whole text.
When the More button is pressed the button changes to Less
Read more string manipulation in w3schools: String Manipulation or
Mozila: String Manipulation
var startStatus = "less";
function toggleText() {
var text = "Here is the text that I want to play around with";
if (text.length > 12) {
if (startStatus == "less") {
document.getElementById("textArea").innerHTML = `${text.substring(0, 12)}...`;
document.getElementById("more|less").innerText = "More";
startStatus = "more";
} else if (startStatus == "more") {
document.getElementById("textArea").innerHTML = text;
document.getElementById("more|less").innerText = "Less";
startStatus = "less";
}
} else {
document.getElementById("textArea").innerHTML = text;
}
}
toggleText();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>
<p id="textArea">
<!-- This is where i want text displayed-->
</p>
<span><a
id="more|less"
onclick="toggleText();"
href="javascript:void(0);"
></a
></span>
</div>
</body>
</html>
This should resolve your problem:
function toggleSeeMore() {
if(document.getElementById("textarea").style.display == 'none') {
document.getElementById("textarea").style.display = 'block';
document.getElementById("seeMore").innerHTML = 'See less';
}
else {
document.getElementById("textarea").style.display = 'none';
document.getElementById("seeMore").innerHTML = 'See more';
}
}
The complete working example is here: http://jsfiddle.net/akhikhl/zLA5K/
Hope this Code you are looking for
HTML:
<div class="showmore">
<div class="shorten_txt">
<h4> ##item.Title</h4>
<p>Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text </p>
</div>
</div>
SCRIPT:
var showChar = 100;
var ellipsestext = "[...]";
$('.showmore').each(function () {
$(this).find('.shorten_txt p').addClass('more_p').hide();
$(this).find('.shorten_txt p:first').removeClass('more_p').show();
$(this).find('.shorten_txt ul').addClass('more_p').hide();
//you can do this above with every other element
var teaser = $(this).find('.shorten_txt p:first').html();
var con_length = parseInt(teaser.length);
var c = teaser.substr(0, showChar);
var h = teaser.substr(showChar, con_length - showChar);
var html = '<span class="teaser_txt">' + c + '<span class="moreelipses">' + ellipsestext +
'</span></span><span class="morecontent_txt">' + h
+ '</span>';
if (con_length > showChar) {
$(this).find(".shorten_txt p:first").html(html);
$(this).find(".shorten_txt p:first span.morecontent_txt").toggle();
}
});
$(".showmore").click(function () {
if ($(this).hasClass("less")) {
$(this).removeClass("less");
} else {
$(this).addClass("less");
}
$(this).find('.shorten_txt p:first span.moreelipses').toggle();
$(this).find('.shorten_txt p:first span.morecontent_txt').toggle();
$(this).find('.shorten_txt .more_p').toggle();
return false;
});
<script type="text/javascript">
function showml(divId,inhtmText)
{
var x = document.getElementById(divId).style.display;
if(x=="block")
{
document.getElementById(divId).style.display = "none";
document.getElementById(inhtmText).innerHTML="Show More...";
}
if(x=="none")
{
document.getElementById(divId).style.display = "block";
document.getElementById(inhtmText).innerHTML="Show Less";
}
}
</script>
<p id="show_more1" onclick="showml('content1','show_more1')" onmouseover="this.style.cursor='pointer'">Show More...</p>
<div id="content1" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
</div>
if more div use like this change only 1 to 2
<p id="show_more2" onclick="showml('content2','show_more2')" onmouseover="this.style.cursor='pointer'">Show More...</p>
<div id="content2" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
</div>
demo
jsfiddle
I'm not an expert, but I did a lot of looking to implement this for myself. I found something different, but modified it to accomplish this. It's really quite simple:
The function takes two arguments, a div containing only the words "show more" [or whatever] and a div containing the originally hidden text and the words "show less." The function displays the one div and hides the other.
NOTE: If more than one show/hide on page, assign different ids to divs
Colors can be changed
<p>Here is text that is originally displayed</p>
<div id="div1">
<p style="color:red;" onclick="showFunction('div2','div1')">show more</p></div>
<div id="div2" style="display:none">
<p>Put expanded text here</p>
<p style="color:red;" onclick="showFunction('div1','div2')">show less</p></div>
<p>more text</p>
Here is the Script:
<script>
function showFunction(diva, divb) {
var x = document.getElementById(diva);
var y = document.getElementById(divb);
x.style.display = 'block';
y.style.display = 'none';
}
</script>
You can also use details HTML tag which does the work for you.
<details>
<summary>Epcot Center</summary>
<p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p>
</details>
Source W3CSchool

How do I use Javascript or jQuery get highlighted text?

How do I get javascript or jquery to grab me text that I've selected/high lighted with my mouse or keyboard?
Similar to the above, this outputs the selected text to a div (adapted from http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language=javascript>
$(document).ready( function() {
var txt = '';
function getSelected()
{
if (window.getSelection) {
txt = window.getSelection();
}
else if(document.getSelection) {
txt = document.getSelection();
}
else if(document.selection) {
txt = document.selection.createRange().text;
}
txt = txt.toString();
return txt;
}
$('#container').mouseup( function() {
$('#message').html(getSelected());
});
});
</script>
<style type="text/css">
#message {
min-height: 20px;
width: 300px;
border: 1px solid orange;
padding: 5px;
}
</style>
<div id="message"></div>
<div id="container">
<p>Text to select</p>
</div>
For textareas, you can use this (as seen on javascript wrap text with tag ):
var val;
el = document.getElementById('textarea');
if (el.setSelectionRange) {
//webkit & ff
var val = el.value.substring(el.selectionStart,el.selectionEnd);
}
else if(document.selection.createRange()) {
// ie
var val = document.selection.createRange().text;
}

Categories

Resources