JS Text change on mouseover - javascript

I am beginner to coding and js. I have been looking to get started on a little project to change text (i.e. the word "cat") to another piece of text (i.e. dog) on hover? Please help, anything simple to get me started.

I guess what you are trying to achieve raises the following two basic questions:
How do you change the text of an element?
How do you trigger this change when hovering over the element?
To answer your first question you may check out this webpage to find out about basic dom manipulation. You can also have a look at the following code snippet to see how to permanently change a text with "cat" to "dog".
var text = document.getElementById('text')
text.textContent = "dog"
<p id="text">
cat
</p>
To answer your second question you should read about eventlistener. In this case particular you probably want to use the events mouseover and mouseout. The following snippet will provide an example of how to use them:
var text = document.getElementById('text')
text.addEventListener("mouseout", function() {
text.textContent = "cat"
})
text.addEventListener("mouseover", function() {
text.textContent = "dog"
})
<p id="text">
cat
</p>
Since you seem to be a new learner I could also recommend you to read about window.onload since you may be running into some trouble when executing the lines like var text = document.getElementById('text') too early.
Also, you could have a look at the difference between innerHTML and textContent as mentioned by Nick Parsons in a comment. It's actually cleaner to use textContent in this case since we only want to change a text.

This code changes the link text to whatever you have in "data-change", and changes it back again on mouse out.
Cat
<script type="text/javascript">
function changeMe(el) {
newText = el.getAttribute('data-change');
oldText = el.innerText;
el.setAttribute('data-change', oldText);
el.innerText = newText;
}
</script>
Test: https://codepen.io/anon/pen/MzBQod

Related

Dynamic text entry with JavaScript

Let me preface this by saying that I am currently a JavaScript beginner, and would really appreciate it if someone could point me in the right direction, as I am currently at a bit of a loss.
I found this pen written in Vue.js. It does a few things, but I am interested in the function wherein text appears in plain html as you type data in the field.
I was wondering how this could be accomplished with JavaScript?
https://codepen.io/mitchell-boland/pen/NVZyjX
computed: {
// Think of this as live updates
reverseString: function() {
if(this.task) {
return this.task.split('').reverse().join('')
}}}})
It's relatively straightforward. You can listen for the "input" event on the textbox and copy the current value of the textbox into another element.
In the case of your example, the text is also being reversed at the same time, for which you need a little bit of extra code.
Here's a runnable demo:
var input = document.getElementById("textIn");
var output = document.getElementById("output");
//listen to the "input" event and run the provided function each time the user types something
input.addEventListener("input", function() {
//this line reverses the typed value
var textOut = this.value.split("").reverse().join("")
//write the output to another element
output.innerText = textOut;
});
<input type="text" id="textIn" />
<div id="output"></div>
P.S. You didn't mention the reversing of text in your question, so if you don't want it you can simplify the above by removing that line and writing the value of the input box directly into the div element, e.g.
var input = document.getElementById("textIn");
var output = document.getElementById("output");
//listen to the "input" event and run the provided function each time the user types something
input.addEventListener("input", function() {
//write the output to another element
output.innerText = this.value;
});
I'll post this as answer:
If you're wondering how the input text turns to a reversed text in the pen, then you might need this:
function reverseText(txt){
document.getElementById("#output").innerText = txt.split("").reverse().join("");
}
<input type="text" onkeyup="reverseText(this.value)" />
<p id="output"></p>

Condition replacement of text in page

I'm working on a simple browser plug in to replace 1 word with another but with the addition of an anchor for a small tooltip/pop up. I have this actually working already but my problem is, if the word to be replaced is within an anchor already, then my </a> closes the already open <a>.
So I need some help with how to only replace a word, as long as its not within an open anchor tag. A follow up to this is to also make sure the target word isn't in an <input> or other inappropriate tags.
My code is:
var regex = new RegExp("\\b" + nativeWord + "\\b", "igm");
var body = $('body');
body.each(function() {
$(this).html(
$(this).html().replace(regex, function() {
counter++;
if(counter > wordSwapLimit) {
return nativeWord;
} else {
return "<a class=\"tooltip\" href=\"#\">" + studyWord + "<span class=\"classic\">" + nativeWord + "</span></a>";
}
})
);
});
I'm suspecting that I might need to write a more complex RegExp but this is my first outing with it so any suggestions would be greatly appreciated!
Update
So I have a test page I work with to see how my code works.
This is part of the original HTML from the page:
<p id="changeArea"> I love chicken but I hate beef. </p>
But with the code shown above and swapping 'chicken' for 'kip', this gets changed to:
<p id="changeArea"> I kip<span class="classic">chicken</span>.com">love <a class="tooltip" href="#">kip<span class="classic">chicken</span></a> but I hate beef. </p>
If I have no anchors around what I am swapping, then it works perfectly and I get a nice rollover tooltip.
Thanks again for your help!
Update 2
As requested, here are 'unprocessed' examples that my plugin might come across when swapping 'chicken' for 'kip':
<p id="changeArea"> I love chicken but I hate beef. </p>
<p id="changeArea2"> Chickenpie? pie-chicken. </p>
What I'm hoping for is the following:
<p id="changeArea"> I love chicken but I hate beef. </p>
<p id="changeArea2"> Chickenpie? pie-<a class="tooltip" href="#">kip<span class="classic">chicken</span></a>. </p>
As you can see in the first line, the html code is left alone, as is text for the word, because it is within a URL and so would break it if my tooltip anchor was put in.
The second line ignores 'chickenpie' because I only want whole word swapping, as per my existing regexp. 'pie-chicken' does get swapped though. This line is processed correctly with existing code.
I'm literally just looking to add additional rules to my existing code that say 'dont replace code and dont replace if within an anchor open tag.
Since you're in JavaScript, you already have access to the DOM. Why would you try using Regexes???
Just iterate through text nodes, ignoring existing links:
(function(elem) {
var recurse = arguments.callee, nodes = elem.childNodes, l = nodes.length, i, t,
getLink = function() {
var a = document.createElement('a'), s = document.createElement('span');
a.href = "#";
a.className = "tooltip";
a.appendChild(document.createTextNode(studyWord));
s.className = "classic";
s.appendChild(document.createTextNode(nativeWord));
a.appendChild(s);
return a;
};
for( i=0; i<l; i++) {
switch(nodes[i].nodeType) {
case 1:
// element - recurse, but not if already a link
if( nodes[i].nodeName != "A") recurse(nodes[i]);
break;
case 3:
// text node, look for keyword
t = nodes[i].nodeValue.search(new RegExp("\\b"+nativeWord+"\\b","i"));
if( t > -1) {
// found it! now to hack around...
t = nodes[i].splitText(t);
t.splitText(nativeWord.length);
t.parentNode.replaceChild(t,getLink());
}
break;
}
}
})(document.body);
Please note: This approach uses Vanilla JS. It is up to you to ensure it is run after the page is loaded. This may be done either by:
Adding the defer attribute to the script, if it is external
Putting the script right before the </body> (or at least after all the content you wish to affect)
Wrapping it in a window.onload handler, or even $(function() {...}) since you're already using jQuery.

How can I create tags using Rangy.js without a class attribute?

I've been playing with Rangy.js for selection ranges and so far really like it. I'm looking to wrap a selection range's text nodes within a certain tag and toggle this upon button click. I have it working great using the cssClassApplierModule with the exception of (and it makes sense due to the name) I HAVE to also give the dom element a class that it's applying to itself.
So right now when I select a range and apply for instance a strong tag, my end result is:
Text text text <strong class="test"> selected text </strong> text text text
And I'd like it to be:
Text text text <strong> selected text </strong> text text text
The code I have so far is as follows:
function gEBI(id) {
return document.getElementById(id);
}
var action;
function toggleAction() {
action.toggleSelection();
}
rangy.init();
// Enable buttons
var cssClassApplierModule = rangy.modules.CssClassApplier;
// Next line is pure paranoia: it will only return false if the browser has no support for ranges,
// selections or TextRanges. Even IE 5 would pass this test.
if (rangy.supported && cssClassApplierModule && cssClassApplierModule.supported) {
action = rangy.createCssClassApplier("test", {
elementTagName: "strong",
elementProperties: { }
});
var toggleActionButton = gEBI(nsID);
toggleActionButton.disabled = false;
toggleActionButton.ontouchstart = toggleActionButton.onmousedown = function () {
toggleAction();
return false;
};
}
I tried "" and null instead of "text" as the css class being passed, and it will toggle, but no longer toggle off and is obviously not the correct solution.
Any help appreciated.. Thanks!
Rangy's CSS class applier won't let you do this, unfortunately. The fundamental problem is that it relies on the CSS class to decide which elements and text nodes to surround or add/remove classes from. It's considerably simpler to detect the presence of a class than the more general case of detecting a style, such as boldness.
I did some work last year on a more ambitious and generic execCommand module that would do what you want. It got as far as a working demo but I got bogged down in tricky edge cases and stopped working on it. I do intend to go back to it but it's likely to be months before anything is ready.

How to append text to '<textarea>'?

I have <textarea> where user can type in his message to the world! Below, there are upload buttons... I would love to add link to uploaded file (don't worry, I have it); right next to the text that he was typing in.
Like, he types in 'Hello, world!', then uploads the file (its done via AJAX), and the link to that file is added in next line to the content of <textarea>. Attention! Is it possible to keep cursor (place where he left to type) in the same place?
All that may be done with jQuery... Any ideas? I know that there are method 'append()', but it won't be for this situation, right?
Try
var myTextArea = $('#myTextarea');
myTextArea.val(myTextArea.val() + '\nYour appended stuff');
This took me a while, but the following jQuery will do exactly what you want -- it not only appends text, but also keeps the cursor in the exact same spot by storing it and then resetting it:
var selectionStart = $('#your_textarea')[0].selectionStart;
var selectionEnd = $('#your_textarea')[0].selectionEnd;
$('#your_textarea').val($('#your_textarea').val() + 'The text you want to append');
$('#your_textarea')[0].selectionStart = selectionStart;
$('#your_textarea')[0].selectionEnd = selectionEnd;
You should probably wrap this in a function though.
You may take a look at the following answer which presents a nice plugin for inserting text at the caret position in a <textarea>.
You can use any of the available caret plugins for jQuery and basically:
Store the current caret position
Append the text to the textarea
Use the plugin to replace the caret position
If you want an "append" function in jQuery, one is easy enough to make:
(function($){
$.fn.extend({
valAppend: function(text){
return this.each(function(i,e){
var $e = $(e);
$e.val($e.val() + text);
});
}
});
})(jQuery);
Then you can use it by making a call to .valAppend(), referencing the input field(s).
You could use my Rangy inputs jQuery plugin for this, which works in all major browsers.
var $textarea = $("your_textarea_id");
var sel = $textarea.getSelection();
$textarea.insertText("\nSome text", sel.end).setSelection(sel.start, sel.end);

how to highlight part of textarea html code

I want to achieve a python version web regexbuddy,and i encounter a problem,how to highlight match values in different color(switch between yellow and blue) in a textarea,there has a demo what exactly i want on http://regexpal.com,but i was a newbie on js,i didn't understand his code meaning.
any advice is appreciated
To save time you should consider using an existing library for this requirement.
Quote from here:
As textarea elements can’t render HTML, this plugin allows you to highlight text inside textarea elements.
jQuery highlightTextarea.
Demo: Codepen
Usage:
$context.highlightTextarea(options);
There is a pre element over the textarea. So when you type anything it is copying the input on the pre element, applying some filters.
For example:
<pre id="view"></pre>
<textarea id="code"></textarea>
When you type on #code it is copying the value, applying filters and adding the HTML to the #view.
var code = document.getElementById("code");
var pre = document.getElementById("pre");
(code).onkeyup = function (){
val = this.value;
val = YourRegex(val);
(pre).innerHTML = val;
};
YourRegex would be a method to match the regex and return some parsed content to the pre, allowing you to customize the appearance of the textarea (that is actually an element over it).
function YourRegex(val)
{
// This function add colors, bold, whatever you want.
if (/bbcc/i.test("bbcc"))
return "<b>" + val + "</b>";
}
#BrunoLM's solution is excellent, but might require more hacking than you're comfortable with. If you're interested (and if jQuery is already in your stack), the following plugin may be worth taking a look at:
http://garysieling.github.io/jquery-highlighttextarea/

Categories

Resources