I'm trying to set a variation of this Javascript: How to detect if a word is highlighted , but I'd like to run the function getSelectedText only if the selected text matches the value of the h1 id
The code I set looks like:
function getSelectedText() {
var x = document.getElementById("titleProduct");
var text = "";
if (typeof window.getSelection === x) {
alert('hey');
text = window.getSelection().toString();
}
return text;
}
function doSomethingWithSelectedText() {
var selectedText = getSelectedText();
if (selectedText) {
document.getElementById("hiddenCTA").className = "visibleCTA";
}
}
var x = document.getElementById("titleProduct");
document.onmouseup = doSomethingWithSelectedText;
I included the alert('hey') inside that if loop to see that is running, just for testing but there is no evidence of it in my tests, nor I can see any errors in the console. The whole code is in http://codepen.io/malditojavi/pen/LWmRvp?editors=1010
In this case, the function should only run if the full string 'Title Of Your Product' is selected, not any other text within the HTML document.
Your if should be:
if (window.getSelection().toString() === x.textContent) {
But it seems your function could just return a boolean indicating if the expected text was matched. As you already know the text in that case, it suffices to return true or false. Here is how I would suggest writing it:
function isSelectedText(txt) {
return window.getSelection().toString().trim() === txt;
}
function doSomethingWhenTextSelected() {
if (isSelectedText(document.getElementById("titleProduct").textContent)) {
document.getElementById("hiddenCTA").className = "visibleCTA";
}
}
document.onmouseup = doSomethingWhenTextSelected;
.hiddenCTA { display: none }
.visibleCTA { display: block }
<h3 id="titleProduct">Title Of Your Product</h3>
hhhh
<div class="hiddenCTA" id="hiddenCTA">Hey, we do price match!</div>
Related
I would like to verify that what the user enters is exactly the same as the name value of the input. I have this working but I need for the input box to appear in green when it is. This is the code I have...
function onKeyUp(el) {
var update_value = el.value;
var inputValue = el.getAttribute('name');
if(update_value == inputValue){
document.getElementById("myDiv").style.borderColor = "green";
}
if (update_value != inputValue) { // el.value is current value, inputValue is the default value
$('[name="actionSave"]').removeClass('disabled');
} else {
$('[name="actionSave"]').addClass('disabled');
}
}
I've got this partly working now...
function onKeyUp(el) {
var update_value = el.value;
var inputValue = el.getAttribute('name');
if(update_value == inputValue){
// alert(update_value+"=="+inputValue);
el.style.borderColor = "#66ff00";
}
if (update_value != inputValue) { // el.value is current value, inputValue is the default value
jQuery('[name="actionSave"]').removeClass('disabled');
} else {
jQuery('[name="actionSave"]').addClass('disabled');
}
}
When I type in the correct response, the text box turns green, however if I change it afterwards it does not change, it remains green. Is there a way to make it go back to the original color?
This question already has answers here:
How do I copy to the clipboard in JavaScript?
(27 answers)
Closed 4 years ago.
I need to copy any selection from a webpage to the clipboard, it can be on a div, text input, password input, span, etc.
I have the following function that does this for me, but the challenge is have the returned value from the function to be set on the clipboard
const getSelectionText = () => {
let text = "";
let activeDomElement = document.activeElement;
let activeDomElementTagName = activeDomElement ? activeDomElement.tagName.toLowerCase() : null;
if (
(activeDomElementTagName === 'textarea') || (activeDomElementTagName === 'input' &&
/^(?:text|search|password|tel|url)$/i.test(activeDomElement.type)) &&
(typeof activeDomElement.selectionStart === "number")
) {
text = activeDomElement.value.slice(activeDomElement.selectionStart, activeDomElement.selectionEnd);
} else if (window.getSelection) {
text = window.getSelection().toString();
}
return text;
}
Any idea, or links to resources would be helpful, thanks
Have a look at the example from w3schools.It is a basic example.
https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
You can also use this -
Just call myFunction with your returned text as an argument.
function myFunction(arg) {
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value",arg);
x.select();
document.execCommand("Copy");
alert("Copied the text: " + x.value);
document.removeChild(x);
}
document.execCommand("copy") this will copied all your selected text !
function copySelectionText(){
var copysuccess // var to check whether execCommand successfully executed
try{
copysuccess = document.execCommand("copy") // run command to copy selected text to clipboard
} catch(e){
copysuccess = false
}
return copysuccess
}
document.body.addEventListener('mouseup', function(e){
var copysuccess = copySelectionText() // copy user selected text to clipboard
if(copysuccess) {
document.getElementById('paste').style.display = "block";
}
}, false)
<h3>Late</h3>
<p>dsfjdslkfjdslkfjdsklfj</p>
<code>Cdoing is godo for a wite </code>
<textarea placeholder="Paste Here with [Ctrl + V ]" style="display:none;" id="paste"> </textarea>
I'm stuck on how to iterate to the next element based on the condition in a function. Once the user highlights the right word and the message well done gets displayed, it should move on to the next definition/word taken from the array onA. At the bottom, I've put a pseudo code, as I don't know how to access the result of the conditional statement from the function.
var onA = [
{t: "grooming", d: "an activity when someone builds an emotional connection with a child to gain their trust for the purposes of sexual abuse or exploitation."},
{t: "cyberbullying", d: "an activity that involves the use of ICT, particularly mobile phones and the internet, deliberately to upset, threaten and intimidate someone else."}
];
function getSelectionHandler(index) {
return function clickHandler() {
var txt = '';
var feedback = document.querySelector("#onA .feedback");
if (window.getSelection) {
txt = window.getSelection().toString();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
// Display the selected text
document.querySelector("#onA .word").innerHTML = txt;
// Change the type of bootstrap alert depending on success
function feed(oldClass, newClass, message) {
feedback.classList.remove(oldClass);
feedback.classList.add(newClass);
feedback.innerHTML = message.bold();
}
// Check if the selected word is correct
if (txt === onA[index].t) {
feed("alert-warning", "alert-success", "Well done!");
} else {
feed("alert-success", "alert-warning", "Try again!");
}
};
}
var i = 0
while (i<onA.length) {
document.getElementById("onA").onclick = getSelectionHandler(i);
document.querySelector("#onA .def").innerHTML += onA[i].d;
if condition in the if statement above is true:
i++
}
Global variable can be used to record the current state. I just write it bear hand, you have to debug it if necessary.
function getSelectionHandler(){
var txt = '';
var feedback = document.querySelector("#onA .feedback");
if (window.getSelection) {
txt = window.getSelection().toString();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
// Display the selected text
document.querySelector("#onA .word").innerHTML = txt;
// Change the type of bootstrap alert depending on success
function feed(oldClass, newClass, message) {
feedback.classList.remove(oldClass);
feedback.classList.add(newClass);
feedback.innerHTML = message.bold();
}
// Check if the selected word is correct
if (txt === onA[index].t) {
feed("alert-warning", "alert-success", "Well done!");
index++; //increase before showing next or checking end
if (checkEnded()){
//all end, show end msg
feed("alert-warning", "alert-success", "Finish!");
}else {
//show next
showNext();
}
} else {
feed("alert-success", "alert-warning", "Try again!");
}
}
function checkEnded(){
return index >= onA.length;
}
function showNext(){
document.querySelector("#onA .def").innerHTML += onA[index].d; //display next item
}
var index = 0; //global index for selecting from the array
document.getElementById("onA").onclick = function(){getSelectionHandler();} //register hanlder onc time only
document.querySelector("#onA .def").innerHTML += onA[index].d; //display first item
I have this code , which popups the highlighted text in the page . The problem I have is that the highlighted text always pops up at the end of the page ?
Does the create range return an integer value due to which I can make it popup at the middle of the line ? Is there any way that the pop up can be popped below the line under which the text is highlighted ?
The code so far is as follows
var getSelected = function() {
var t = '';
if(window.getSelection) {
t = window.getSelection();
} else if(window.selection) {
t=window.selection.createRange();
}
return t;
}
$(document).ready(function(){
$(document).bind("mouseup",mouseup);
$(document).bind("mousedown",mousedown);
});
var mouseup=function(){
$('div#pop-up').show();
var st = getSelected();
document.getElementById("pop-up").innerHTML=st;
}
var mousedown = function(){
$('div#pop-up').hide();
}
The above is the JS file for it . While the html just has a div with an id of pop-up
The problem isn't within the selector . But the problem is where it popups . It popsup at the end of the page due to the innerHTML but I want it to popup near where the text is selected . How do I do that ?
The selection range is an object that describes what text you've highlighted, in which element, and its general state.
The reason there's an if there is because this is a semi-recent (been around for years, just not 100% compatible, so few use it) standard, and different vendors used different implementations.
If you're on a browser which supports getSelection, then get the object that function returns...
...else, if your browser has a window.selection object, which holds methods for reading the actual selection, then do that.
It's like the old days of doing event-listening.
Now, everything is .addEventListener.
Once upon a time, it was:
if (document.addEventListener) { el.addEventListener(evt, func, false); }
else {
func = function () { func.call(el, window.event); };
el.attachEvent(evt, func);
}
Or XMLHttpRequest versus window.ActiveXObject("msxml2.xmlhttp");s...
remove the else if condition it should be just else in your case:
var getSelected = function() {
var t = '';
if(window.getSelection) {
t = window.getSelection();
} else {
t=window.selection.createRange();
}
return t;
}
I'm trying to get the values from the and a checkbox, and put the value in a text box OR add the dropdown and checkbox if both are selected and put that into a text box. There is a JavaScript error in the code, which you can see in the link below, in IE but it works correctly in Chrome. Any guidance on this?
function TotAmt() {
var DA = +document.getElementById("Donation").options[Donation.selectedIndex].value;
if (document.form1.somename.checked == true) {
document.form1.Summary.value = parseInt(DA) + parseInt(500);
} else {
document.form1.Summary.value = parseInt(DA);
}
}
View sample code
You get rid of that specific error in jsFiddle by not wrapping the javascript in the head. Then use getElementById function in your ToAtm() function like this:
function fnchecked(blnchecked) {
if (blnchecked) {
document.getElementById("CoatSizeDiv").style.display = "";
} else {
document.getElementById("CoatSizeDiv").style.display = "none";
}
}
function TotAmt() {
var DA = +document.getElementById("Donation").options[Donation.selectedIndex].value;
if (document.getElementById("somename").checked == true) {
document.getElementById("Summary").value = parseInt(DA) + parseInt(500);
} else {
document.getElementById("Summary").value = parseInt(DA);
}
}
UPDATED CODE