Need To Convert Text To UpperCase and Lowercase When Clicked - javascript

I know nothing about JavaScript, and I'm sure this is an easy thing to do, but I've been bashing my brain for the past three hours trying to figure it out.
What I want is to have some text, say Test.com, that when clicked will transform all the letters to uppercase (TEST.COM). If the user clicks again, the text will go to all lowercase(text.com). On the third click the text goes back to the original form (Test.com).
Is this possible?

var count = 1;
$('.text').click(function() {
$(this).toggleClass('uppercase', count === 2);
$(this).toggleClass('lowercase', count === 3);
if (count === 3) {
count = 0
}
count++;
});
.uppercase {
text-transform: uppercase;
}
.lowercase {
text-transform: lowercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="text">CamelCase 1 </span>

Here's the long-winded vanilla JS version:
// grab the element containing the text
var div = document.querySelector('#test');
// grab the text
var text = div.innerHTML;
// save a copy of the text
var originalText = div.innerHTML;
// set `toggle` to O for original
// L = lowercase, U = uppercase
var toggle = 'O';
// add an click listener to the element containing the text
div.addEventListener('click', function () {
// toggle between the states updating the text
// of the element with each new click
switch (toggle) {
case 'O':
div.innerHTML = text.toUpperCase();
toggle = 'U';
break;
case 'U':
div.innerHTML = text.toLowerCase();
toggle = 'L';
break;
case 'L':
div.innerHTML = originalText;
toggle = 'O';
break;
}
}, false)
DEMO
And if you wanted to get this working for multiple instances of text on the page, something like this would work. Ideally you'd want to use event propagation for this, but since the layout of your page might change in the future it's probably not worth the risk:
;(function () {
// grab all the elements
var divs = document.querySelectorAll('.test');
// status is used to keep track of where in the cycle each text item is
var status = {};
for (var i = 0, l = divs.length; i < l; i++) {
var div = divs[i];
var key = div.innerHTML.toLowerCase();
// update the status object with the initial text values
status[key] = {
status: 'O',
originalText: div.innerHTML
};
// add the listener like last time
// except this time we monitor the status object for
// for each text instance
div.addEventListener('click', function () {
var text = this.innerHTML.toLowerCase();
var key = status[text].originalText.toLowerCase();
var toggle = status[key].status;
var originalText = status[key].originalText;
switch (toggle) {
case 'O':
this.innerHTML = originalText.toUpperCase();
status[key].status = 'U';
break;
case 'U':
this.innerHTML = originalText.toLowerCase();
status[key].status = 'L';
break;
case 'L':
this.innerHTML = status[key].originalText;
status[key].status = 'O';
break;
}
}, false);
}
}());
DEMO

Define 2 CSS classes.
.ucase {text-transform:uppercase;}
.lcase {text-transform:lowercase;}
Use a combination of jQuery .hasClass() .removeClass() and .addClass() to switch the cases.
Remove all classes from the text to return to original state.
jQuery(document).ready(function() {
jQuery(".textitem").click(function() {
$t = jQuery(this);
if($t.hasClass("ucase")) {
$t.removeClass("ucase").addClass("lcase");
} else if($t.hasClass("lcase")) {
$t.removeClass("lcase");
} else {
$t.addClass("ucase");
}
});
});
Fiddle: https://jsfiddle.net/ptj1ke8y/

Perhaps not the most elegant solution, but you can count the clicks (modulus 3), and adjust the text according to the number and cycle through your 3 cases.
var i = 0;
var cl = $('#text').text();
$('#text').click(function() {
var str = $(this).text();
if (i % 3 == 0) {
$('#text').html(str.toUpperCase());
}
if (i % 3 == 1) {
$('#text').html(str.toLowerCase());
}
if (i % 3 == 2) {
$('#text').html(cl);
}
i++
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="text">Text</div>

You can use .toUpperCase() and .toLowerCase() JavaScript methods to change the case of any text.
Since you're using jQuery then you can use the .text() jQuery method to get and set the text content of any DOM node.
You need to store somewhere the original value of your text so that you can get it after the third click, and the jQuery .data() method would be good for this because that way you can easily have few elements on one page that behaves this way.
You can write something like this to make all elements with class "test" behave in a way that you have described:
$('.test').click(function () {
var $this = $(this),
data = $this.data('clicker');
if (!data || !data.text) {
data = {
text: [
$this.text(),
$this.text().toUpperCase(),
$this.text().toLowerCase()
],
step: 0
};
}
data.step = (data.step + 1) % 3;
$this.text(data.text[data.step]);
$this.data('clicker', data);
});
See: DEMO for an example of how it works with 3 elements simultaneously.

First use click() to event handler to the "click" and then use .hasClass(), removeClass() and addClass() to do and use css text-transform
HTML file
<div id="trigger">click me to transform</div>
CSS File
.uppercase { text-transform: uppercase; }
.lowercase { text-transform:lowercase; }
Javascript file
$( document ).ready(function() {
$( "#trigger" ).click(function() {
if($( "#trigger" ).hasClass( "uppercase" )) {
$(this).removeClass('uppercase').addClass('lowercase');
}
else {
$(this).removeClass('lowercase').addClass('uppercase');
}
});
});
Try to play the Sandbox

I think this is what you want (button caption changes to tell what is it going to do and changes the text):
<form name="form1" method="post">
<input name="instring" id="instring" type="text" value="this is the text string" size="30">
<input type="button" id="button" name="Convert" value="Make Uppercase >>" onClick="makeUppercase();">
<input name="outstring" type="text" id="outstring" value="" size="30">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function makeUppercase(){
if( $('#button').val()=="Make Uppercase >>"){
$('#button').attr("value","Make Lowercase >>");
$('#outstring').attr('value', $('#instring').attr('value').toUpperCase());
} else if($('#button').val()=="Make Lowercase >>") {
$('#button').attr("value","Make Original >>");
$('#outstring').attr('value', $('#instring').attr('value').toLowerCase());
} else{
$('#button').attr("value","Make Uppercase >>");
$('#outstring').attr('value', $('#instring').attr('value'));
}
}
</script>

Related

Getting text selection with javascript, then modify text

I have a text on an HTML page. If the user selects a word, I can retrieve the selected word and know exactly what he or she selected. However, I now want to also modify this word on the screen and make it bold. But I do not know how I would do this, since I only know the word clicked, but do not see an easy way to find the word in the HTML and modify it. I could of course search for it, but there is the risk of a word appearing multiple times.
A different way I thought about would be to give each word a unique idea and have something like this:
<span id="1">The</span>
<span id="2">fox</span>
<span id="3">jumps</span>
<span id="4">over</span>
<span id="5">the</span>
<span id="6">fence</span>
But I do not like this solution. This, too, seems overly complicated, does it not? Any suggestions how else I could access the exact words selected?
You can dynamically create a span surrounding the selected word:
const p = document.querySelector('p');
p.addEventListener('mouseup', () => {
const range = document.getSelection().getRangeAt(0);
do {
const charBefore = range.startContainer.textContent[range.startOffset - 1];
if (charBefore.match(/\s/)) break;
range.setStart(range.startContainer, range.startOffset - 1);
} while (range.startOffset !== 0);
do {
const charAfter = range.endContainer.textContent[range.endOffset];
if (charAfter.match(/\s/)) break;
range.setEnd(range.endContainer, range.endOffset + 1);
} while (range.endOffset !== range.endContainer.textContent.length);
const span = document.createElement('span');
span.style.fontWeight = 'bold';
range.surroundContents(span);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>The fox jumps over the fence.</p>
No need of jQuery, also no need of IDs for each <span>.
The idea is to add a class to the span once it is clicked and later you can retrieve all elements with that bolded class.
Here is a solution with pure Javascript:
// comments inline
var spans = document.getElementsByTagName('span'); // get all <span> elements
for(var i=0, l = spans.length; i<l; i++){
spans[i].addEventListener('click', function(){ // add 'click' event listener to all spans
this.classList.toggle('strong'); // add class 'strong' when clicked and remove it when clicked again
});
}
.strong {
font-weight: bold;
}
<span>The</span>
<span>fox</span>
<span>jumps</span>
<span>over</span>
<span>the</span>
<span>fence</span>
Read up: Element.getElementsByTagName() - Web APIs | MDN
$("p").mouseup(function() {
var selection = getSelected().toString();
$(this).html(function(){
return $(this).text().replace(selection, '<strong>' + selection +'</strong>');
});
});
var getSelected = function(){
var t = '';
if(window.getSelection) {
t = window.getSelection();
} else if(document.getSelection) {
t = document.getSelection();
} else if(document.selection) {
t = document.selection.createRange().text;
}
return t;
}
strong{ font-weight: bold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>The fox jumps over the fence.</p>

Using a javascript button to change html, with multiple values that are picked using an auto incrementing number

Basic html:
<button id="changer">Changer button</button>
<div id="text"> </div>
"Changer" is the button element in html, "text" is the div tag in which our text will be placed.
var selector = 0;
We set the selector to 0. Next, every time the button "changer" is clicked, we add 1 to the selector var, unless it has reached its max value of 14, in which case we start over. And based on the selector value, we pick from the available text values.
document.getElementById("Changer").onclick = function () {
if (selector < 14) {
selector++;
}
else {
selector = 0;
selector++;
}
document.getElementById("text").innerHTML = text;
}
if (selector = 1 ){
text = "<p>this is text 1</p>";
if (selector = 2 ){
text = "<p>this is text 2</p>";
etc...
The problem is, the function upon being clicked jumps right to the last text value available. How do I fix this? Will add live example soon if needed.
Your are assigning the selector inside the if condition to a value.
if(selector = 1) {...
What you actually want to do is check if the selectors value is equal to something like so:
if(selector == 1) {...
But you do not need to repeat the check, you can simply do:
var selector = 0;
var btn = document.getElementById('changer');
var output = document.getElementById('text');
btn.addEventListener('click', function() {
if (selector < 14) {
selector++;
output.innerHTML = "<p>this is text " + selector + "</p>";
} else {
selector = 0;
output.innerHTML = "";
}
})
<button id="changer">Changer button</button>
<div id="text"> </div>

TextBox create div javascript

I want to create different "div" in the body when the user enter the number of div in the textbox
For example, with the markup for my textbox: <input type="text" id="numberDiv" maxlength="1">
I am using the following JS:
<script>
$(document).ready(
function () {
$('#numberDiv').keyup(
function () {
var s = $("#numberDiv").val();
var nbrDiv = parseInt(s);
for(var i = 0; i <= nbrDiv; i++)
{
var iDiv = document.createElement('div');
iDiv.id = 'div';
document.getElementsByTagName('body')[0].appendChild(iDiv);
iDiv.innerHTML = "I'm a div";
}
})
});
</script>
My problem is when I put for example "1" in the textbox it creates 1 div but when I press an other key (for example: enter, alt, ...) it creates another div even if my input has the maxlength="1". How can I disable the pressing on another key when my first number is in the textbox.
First of all, you shouldn't use the same id for all of the divs. So instead of iDiv.id = 'div' you might want to do this:
iDiv.attr('id', 'div[' + i + ']');
I'm not sure about your requirements, but you might also want to check the number of divs before creating new ones:
$('#numberDiv').keyup(function() {
var s = $(this).val();
var currentDivsCount = $('body > div').length;
var nbrDiv = parseInt(s, 10) - currentDivsCount;
if (isNaN(nbrDiv)) return;
var iDiv;
for (var i = 0; i < Math.abs(nbrDiv); i++) {
if (nbrDiv > 0) {
iDiv = $('<div>I\'m a div</div>');
iDiv.attr('id', 'div[' + (currentDivsCount + i) + ']');
iDiv.appendTo('body');
} else {
$('body > div:last').remove();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="numberDiv" maxlength="1">
you can mask your input like so:
first Import the jQuery mask library,
Textbox : <input type="text" id="numberDiv" maxlength="1">
$(document).ready(
function () {
$('#numberDiv').mask('0');
});
this will only allow 1 number (digit character) to be in the box at a time
look here for more examples
and here to download the mask plugin
either you put the check on keycode for using event, if it is for numeric value then only run the logic. simple if in function will work.
<script>
$( "#whichkey" ).on( "keydown", function( event ) {
if( event.which < // range for 1 to 9){
//logic comes here
}
});
</script>
or you can add code to remove innerhtml before adding the div. So even if user press anyother key like enter. It will delete the innerhtml and then add the 1 div.

Determining a character of a sentence when clicked on

On a random break I found myself wondering if it would be possible to use jQuery to determine a single character within a sentence when it is clicked on.
For example:
This
When the user clicks on first h, jQuery would return this to me.
The only way I could think of doing this would be to wrap each character within the sentence in a span with a class of its letter such as the following example:
<span class="clickable T">T</span>
<span class="clickable h">h</span>
<span class="clickable i">i</span>
<span class="clickable s">s</span>
Followed by a $('.clickable').click(function()) that would return its second class.
My question is: is this the most efficient way to do this?
Obviously wrapping every single letter of the document in span tags is not efficient.
I was able to spin something up that works in Chrome at least. Basically, when you click on a letter, it then triggers a double clicks which selects the word. We get the selection which actually gives us the text of the entire target element. From that, we get the letter that was clicked. We remove the selection and do what we want with the letter.
Fiddle here
$(function(){
$(document).click(function(e){
var target = e.target;
$(target).dblclick();
}).dblclick(function(){
var selection,
node,
text,
start,
end,
letter;
if (window.getSelection) {
selection = document.getSelection();
node = selection.anchorNode;
if (node.nodeType === 3) {
text = node.data;
start = selection.baseOffset;
end = selection.extentOffet;
if (!isNaN(start)) {
letter = text.substr(start, 1);
}
}
window.getSelection().removeAllRanges()
} else if(document.selection) {
//continue work here
}
if (letter) {
alert(letter);
}
});
});
You could return the innerHTML as well with:
$('.clickable').on('click', function(){
alert($(this).html());
});
As for a more efficient way to do it...maybe try this:
in Javascript/jQuery, how to check a specific part of a string and determine if it is a whitespace or letter?
You can do it with this script
$('.clickable').on('click', function(){
var html = $(this).text(); // if you want the text inside the span
var index = $(this).index(); // if you want the position among siblings
var classes = $(this).attr('class').split(" ");
var secondClass = getSecondClass(classes);
});
function getSecondClass(classArray){
if(classArray.length<2){
return null;
}else{
return classArray[1];
}
}
I've also included the html and index variables if you want to do something else with the clicked element.
Basically you split the classes of the element by spaces and then check if the array has less than two elements, in that case it returns null, otherwise it returns the second element.
jsFiddle
Well wrapping all text dyanamically with span tag , it is possible what you were looking for
JS
$(function(){
var lengthText = $('#singlecharacter').text().length;
var textValue = $('#singlecharacter').text();
var textArray = textValue.split('');
var newText = new Array();
for (var i = lengthText - 1; i >= 0; i--) {
newText[i] = "<span class='sp'>"+textArray[i]+"</span>";
};
$('#singlecharacter').html(newText);
$('.sp').click(function()
{
alert($(this).text());
});
});
HTML
<div id='singlecharacter'>THIS</div>
DEMO JSFIDDLE

CKEDITOR - Apply bold to numbered list including numbers

I am facing an issue with the numbered list in ckeditor. When I try to bold some text in li, only the text is getting bold, without the preceding number. This is how it looks like,
One
Two
Three
It should be like this
2. Two
When I check the source, I found the code like below
<li><strong>Two</strong></li>
I would like to know is there any way to change the working of bold button, so that it will add something like below
<li style="font-weight:bold">Two</li>
<p> Hello <strong>World</strong></p>
I tried to solve your problem.
My solution isn't the best, because I guess that create a bold plugin, that takes care about list items would be the best solution.
I make it without using jQuery; however, using it the code should became simpler and more readable.
First of all, we need to define something useful for the main task:
String trim. See this.
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
String contains. See this
String.prototype.contains = function(it) {
return this.indexOf(it) != -1;
};
First child element. The following function obtains the first child element, or not-empty text node, of the element passed as argument
function getFirstChildNotEmpty(el) {
var firstChild = el.firstChild;
while(firstChild) {
if(firstChild.nodeType == 3 && firstChild.nodeValue && firstChild.nodeValue.trim() != '') {
return firstChild;
} else if (firstChild.nodeType == 1) {
return firstChild;
}
firstChild = firstChild.nextSibling;
}
return firstChild;
}
Now, we can define the main two functions we need:
function removeBoldIfPresent(el) {
el = el.$;
var elStyle = el.getAttribute("style");
elStyle = (elStyle) ? elStyle : '';
if(elStyle.trim() != '' && elStyle.contains("font-weight:bold")) {
el.setAttribute("style", elStyle.replace("font-weight:bold", ''));
}
}
CKEDITOR.instances.yourinstance.on("change", function(ev) {
var liEls = ev.editor.document.find("ol li");
for(var i=0; i<liEls.count(); ++i) {
var el = liEls.getItem(i);
var nativeEl = el.$.cloneNode(true);
nativeEl.normalize();
var firstChild = getFirstChildNotEmpty(nativeEl);
if(firstChild.nodeType != 1) {
removeBoldIfPresent(el);
continue;
}
var firstChildTagName = firstChild.tagName.toLowerCase()
if(firstChildTagName == 'b' || firstChildTagName == 'strong') {
//TODO: you also need to consider the case in which the bold is done using the style property
//My suggest is to use jQuery; you can follow this question: https://stackoverflow.com/questions/10877903/check-if-text-in-cell-is-bold
var textOfFirstChild = (new CKEDITOR.dom.element(firstChild)).getText().trim();
var textOfLi = el.getText().trim();
if(textOfFirstChild == textOfLi) {
//Need to make bold
var elStyle = el.getAttribute("style");
elStyle = (elStyle) ? elStyle : '';
if(elStyle.trim() == '' || !elStyle.contains("font-weight:bold")) {
el.setAttribute("style", elStyle + ";font-weight:bold;");
}
} else {
removeBoldIfPresent(el);
}
} else {
removeBoldIfPresent(el);
}
}
});
You need to use the last release of CkEditor (version 4.3), and the onchange plugin (that is included by default in the full package).
CKEditor 4.1 remove your classes, styles, and attributes that is not specified in its rules.
If that's the problem, you might want to disable it by adding this line:
CKEDITOR.config.allowedContent = true;
Here is full code to use it:
window.onload = function() {
CKEDITOR.replace( 'txt_description' );
CKEDITOR.config.allowedContent = true; //please add this line after your CKEditor initialized
};
Please check it out here
<ul class="test">
<li><span>hello</span></li>
</ul>
.test li
{
font-weight:bold;
}
.test li span
{
font-weight:normal;
}

Categories

Resources