Reset variable onclick event - javascript

I have a Javascript like given below, what it does is, it calls
doSomethingWithSelectedText
function which checks that if any text is selected (using function getSelectedObj).
getSelectedObj returns an object.
The problem is that div #text gets updated everytime some text is selected. And div #search opens the new google tab searching the highlighted/ selected text.
But it stops updating after that on any other selection.
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
function getSelectedObj() {
var selObj = {};
selObj.text = '';
if (typeof window.getSelection != "undefined") {
selObj.rect = window.getSelection().getRangeAt(0).getBoundingClientRect() ;
selObj.text = window.getSelection().toString();
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
// this block not used in new versions of chrome, mozilla and IE11
selObj.text = document.selection.createRange().text;
}
return selObj;
}
function doSomethingWithSelectedText(e) {
var selectedObj = getSelectedObj();
if (selectedObj.text) {
document.querySelector('#popup').style.display = 'block';
document.querySelector('#popup').style.top = e.clientY - 40;
document.querySelector('#popup').style.left = e.clientX + 20;
document.querySelector('#text').innerHTML = selectedObj.text;
document.querySelector('#search').addEventListener('click', function (e) {
window.open('https://www.google.com/search?q=' + selectedObj.text);
});
}
else {
document.querySelector('#popup').style.display = 'none';
selectedObj.text = '';
}
}
May be it is because of the addEventlistener is defined inside if () of the mouseup event. And it does not get updated. I don't know how to handle this.
index.html
<div id="popup">
<div id ="text"></div>
<div id="search" class="fa fa-search"></div>
<div id="save" class="fa fa-file"></div>
</div>
styles.css
#popup{
display: none;
background-color: orange;
color: white;
position: absolute;
z-index: 1000;
width:100px;
height: 50px;
}
#search,#save {
display: inline-block;
padding: 15px;
font-size: 20px;
}

You should indeed put the event handler outside of your function, as you will be stacking up handlers that all will be executed on the next search click.
Here is an update of your code with the changes marked with ***:
document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;
function getSelectedObj() {
var selObj = {};
selObj.text = '';
if (typeof window.getSelection != "undefined") {
// ***Additional safety to avoid runtime errors
if (window.getSelection().rangeCount) {
selObj.rect = window.getSelection().getRangeAt(0).getBoundingClientRect() ;
selObj.text = window.getSelection().toString();
}
} else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
// this block not used in new versions of chrome, mozilla and IE11
selObj.text = document.selection.createRange().text;
}
return selObj;
}
// ***Variable for retaining the search string
var searchStr = '';
// ***Capture mouseup instead of click, so we can prevent the document level
// handler to get called.
document.querySelector('#search').addEventListener('mouseup', function (e) {
window.open('https://www.google.com/search?q=' + searchStr);
return false; // ***Cancel bubbling to document.
});
function doSomethingWithSelectedText(e) {
var selectedObj = getSelectedObj();
if (selectedObj.text) {
console.log('text:' + selectedObj.text);
document.querySelector('#popup').style.display = 'block';
document.querySelector('#popup').style.top = e.clientY - 40;
document.querySelector('#popup').style.left = e.clientX + 20;
// ***Use textContent instead of innerHTML
document.querySelector('#text').textContent = selectedObj.text;
// ***Store search string to be used when launching search
searchStr = selectedObj.text;
} else {
document.querySelector('#popup').style.display = 'none';
}
}

Related

Can anybody help me out with my Darkmode?

I want do have a basic Darkmode linked to a key press. I'am a Beginner in JavaScript and i cannot get it to work. I want it like, you press a key, the Darkmode turns on with a Cookie over js-cookie, and I press the same Key again to turn off the Darkmode and delete the cookie. Can anybody help me?
There is my Code:
var elem = document.getElementById("folie");
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
let zahl = 1;
if (key.keyCode == "70") {
if (zahl == 1) {
zahl++
dark()
Cookies.set("Darkmode", "An");
}
if (zahl == 2) {
zahl--
Cookies.remove("Darkmode")
}
}
}
var DarkCookie = Cookies.get("Darkmode");
if (DarkCookie == 'An') {
dark();
}
function dark() {
var element = document.body;
element.classList.toggle("dark-mode");
}
Edit:
Ok i've got it:
let CookieDarkMode = false;
function toggleDarkMode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode === 70) { //"F" has been pressed
CookieDarkMode = !CookieDarkMode;
console.log("Cookie Dark mode: " + CookieDarkMode);
toggleDarkMode();
if (CookieDarkMode) {
Cookies.set("Darkmode", "An");
}else {
Cookies.remove("Darkmode");
}
}
};
var DarkCookie = Cookies.get("Darkmode")
if (DarkCookie == 'An') {
CookieDarkMode = true;
toggleDarkMode();
}
You don't have to store a number. You can just get the previous cookie value with a boolean
let CookieDarkMode = false;
function toggleDarkMode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode === 70) { //"F" has been pressed
CookieDarkMode = !CookieDarkMode;
console.log("Cookie Dark mode: " + CookieDarkMode);
toggleDarkMode();
}
};
body {
background-color: ghostwhite;
}
.dark-mode {
background-color: black;
color: white;
}
<body>
<p>Lorem Ipsum</p>
</body>
your problem is on your checkKeyPress function, you always check for the zahl value, but it will always start as 1.
for demostration purposes you are doing this basically:
function sum(){
let zahl = 1;
zahl++
console.log(zahl)
}
// you will never see a 3, because you are creating `zhl`
// in each call with a value of 1
sum();
sum();
sum();
sum();
therefore, each time you check for the zahl variable, it will be 1 and will always enter the if that turns on the darkmode.
the solution for your code would be to move the zahl variable outside the function scope:
let zahl = 1; // outside the function scope
var elem = document.getElementById("folie");
window.addEventListener("keydown", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode == "70") {
if (zahl == 1) {
zahl++
dark()
Cookies.set("Darkmode", "An");
}else if (zahl == 2) {
zahl--
Cookies.remove("Darkmode")
dark(); //you should call dark here as well to toggle to the other mode.
}
}
}
var DarkCookie = Cookies.get("Darkmode");
if (DarkCookie == 'An') {
dark();
}
function dark() {
var element = document.body;
element.classList.toggle("dark-mode");
}
note: it doesn't look like the best implementation, it would be easier to read if you use a boolean for the state of the mode or if you want multiple types, you can use the name as a key for each of the modes.

javascript getSelection give me value twice

here is my question.I am developing a translation chrome extension,and I want that the yellow page shows and gives me the translation when I select word.
this is my code
var txt = null;
document.onmouseup = function(e) {
e = e || window.event;
console.log("upbf txt:" + txt);
txt = funGetSelectTxt(); //get Select word
console.log("up txt:" + txt);
if (check(txt)) {
mydivm.style.display = "block";
//translate and show
}
};
document.onmousedown = function(e) {
txt = "";
var mydivm = document.getElementById("fgbnbb");
if (mydivm.style.display == "block") {
if (!isinclude(e, mydivm)) {
mydivm.style.display = "none";
}
}
console.log("down txt:" + txt);
};
var funGetSelectTxt = function() {
if (window.getSelection) {
return window.getSelection();
}
else if (document.getSelection) {
return document.getSelection();
}
else {
var selection = document.selection &&
document.selection.createRange();
if (selection.text) {
return selection.text;
}
return false;
}
return false;
};
Well,the question is,if I select a word in the html tag <p> or some other,it work well,but if I select a html tag <text>,it has some problem.
the first I selected,the page show and down well,then I click on the text,it show again(in my wish,it will hide),and in the three time,it hide.
I don't know why.the console log in the three time, I want know why and how to solve that .

Creating Dynamic Fullscreen and Minimize Div Functions

The screen displays 3 dynamically created and loaded divs. The problem I'm having is getting the resize to work when I try to make the divs go full screen. (Click the front button and the 2nd on the back). When using the select option on top, the resize works perfectly, but the fullscreen does not have the same effect.
This is my plunkr: http://plnkr.co/edit/qYxIRjs6KyNm2bsNtt1P
This is my current resize function:
for(i = 0; i<numOfDivs.length; i++){
var flipTarget = document.getElementById(flipDiv[i]);
addResizeListener(flipTarget, function() {
for(j = 0; j<numOfDivs.length; j++){
var style = window.getComputedStyle(flipTarget);
divWidth = parseInt(style.getPropertyValue('width'), 10);
divHeight = parseInt(style.getPropertyValue('height'), 10);
width = divWidth - margin.left - margin.right;
height = divHeight - margin.top - margin.bottom;
document.getElementById(frontDivNames[j]).innerHTML = '<span style="font-size: 40px; font-family:icons; cursor:pointer" id="flip" onclick="flipper(\''+flipperDivNames[j]+'\')"></span>';
makeTestGraph();
makeSliderGraph();
};
});
}
Any help on hiding all the other divs and making them reappear later would also be greatly appreciated. This has taken a few days of work and I have gotten almost nowhere despite rewriting the code several times.
Thanks for the help.
Is there something wrong with the javascript fullscreen api???
<script>
var fullscreen;
SetFullscreen = function DetectFullscreen(el){
DesktopFullScreen = function ToggleFullScreen(el){
function cancelFullScreen(el) {
if (window.document.exitFullscreen) {
window.document.exitFullscreen();
} else if (window.document.webkitExitFullscreen) {
window.document.webkitExitFullscreen();
} else if (window.document.mozCancelFullScreen) {
window.document.mozCancelFullScreen();
} else if (window.document.msExitFullscreen) {
window.document.msExitFullscreen();
}
return undefined;
}
function requestFullScreen(el) {
// Supports most browsers and their versions.
var requestMethod = document.getElementById(el).requestFullScreen || document.getElementById(el).webkitRequestFullScreen || document.getElementById(el).mozRequestFullScreen || document.getElementById(el).msRequestFullscreen;
if (requestMethod) { // Native full screen.
requestMethod.call(document.getElementById(el));
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
return true;
}
if (fullscreen){
fullscreen = cancelFullScreen(el);
}
else{
fullscreen = requestFullScreen(el);
}
}
MobileFullScreen = function ToggleFullScreen(el){
function cancelFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="";
return undefined;
}
function requestFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="#"+el+" {position:fixed;top:0px;left:0px;width:100%;height:100%;}";
return true;
}
if (fullscreen){
fullscreen = cancelFullScreen(el);
}
else{
fullscreen = requestFullScreen(el);
}
}
if( navigator.userAgent.match(/mobile/i)){
MobileFullScreen(el);
}
else{
DesktopFullScreen(el);
}
}
</script>
<style>
div{background:white;}
</style>
<style id="fullscreenstyle">
</style>
<div id="fullscreen" onclick="SetFullscreen(this.id)">hello</div>
Following on from your comments are you looking for something like this?
<script>
function cancelFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="";
selectedElement = document.getElementById(el);
selectedElement.setAttribute("onclick","requestFullScreen(this.id)");
document.body.innerHTML=bodysave;
return undefined;
}
function requestFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="#"+el+" {background:pink;position:fixed;top:0px;left:0px;width:97%;height:97%;}";
selectedElement = document.getElementById(el);
bodysave = document.body.innerHTML;
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
document.body.appendChild(selectedElement);
selectedElement.setAttribute("onclick","cancelFullScreen(this.id)");
return true;
}
</script>
<style>
div{background:white;}
</style>
<style id="fullscreenstyle">
</style>
<div id="fullscreen" onclick="requestFullScreen(this.id)">hello</div>
<div id="fullscreen2" onclick="requestFullScreen(this.id)">hello</div>
<div id="fullscreen3" onclick="requestFullScreen(this.id)">hello</div>

Problems with my script which doesnt show on chrome

im having problem, somehow my script if (myStringOld == myString) and if (regex.test(myString)) doesn't work on chrome, i cant figure it out why. myString and myStringOld is the date (format 2015-06-05) Can someone explain me or help to fix it. Because all the type it types else alert.
var myString = txtCellEditor.value;
var myStringOld = oldvalue.value;
if (myStringOld != myString) {
if (regex.test(myString)) {
document.getElementById('cellValueEditorDiv').style.display = 'none';
document.getElementById(cellId).style.border = 'none';
}
else {
alert("Bad date format. yyyy-mm-dd");
}
} else {
alert("You haven't changed the date.");
}
This one works perfectly in Chrome Version 44.0.2403.107 m:
HTML
<div id="cellValueEditorDiv">
<input id="txtCellEditor" value="2012-12-20" />
</div>
<button id="submit">Test it</button>
CSS:
div {
width: 200px;
padding: 12px;
background: white;
}
JavaScript/jQuery:
var oldvalue = "";
var regex = /^\d{4}([./-])\d{2}\1\d{2}$/;
$(document).ready(function () {
$('#submit').click(function () {
var myString = document.getElementById('txtCellEditor').value;
var myStringOld = oldvalue;
if (myStringOld != myString) {
if (regex.test(myString)) {
document.getElementById('cellValueEditorDiv').style.background = 'green';
//document.getElementById(cellId).style.border = 'none';
} else {
document.getElementById('cellValueEditorDiv').style.background = 'red';
alert("Blogas datos formatas arba blogai įvesta data. yyyy-mm-dd");
}
oldvalue = "";
} else {
alert("Nepakeitėte keičiamos datos.");
}
});
});
Try it out:
http://jsfiddle.net/1drygub7/3/

Text and cursor styles changed via JavaScript: browser compatibility problems

i have a navigation bar that uses JavaScript to track its state and to update text and cursor style attributes accordingly. This works as intended in Firefox 26.0, but not in Chrome 32.0.1700.76; in Chrome, it appears to do nothing. A short script that illustrates this is:
var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var foo_on = true;
function turn_on(x) {
x.style = "color: #42A6FF; cursor: pointer;";
x.onmouseover = function () { x.style = "color: #444444; cursor: pointer;"; };
x.onmouseout = function () { x.style = "color: #42A6FF; cursor: pointer;"; };
}
function turn_off(x) {
x.style = "color: #BBBBBB; cursor: default;";
x.onmouseover = null;
x.onmouseout = null;
}
function toggle(caller) {
if((foo_on && caller == 'bar') || (!foo_on && caller == 'foo')){ return; }
if(foo_on){
turn_off(foo);
turn_on(bar);
}
else{
turn_on(foo);
turn_off(bar);
}
foo_on = !foo_on;
}
function init() {
foo_on = true;
turn_on(foo);
turn_off(bar);
}
window.onload = init();
My document layout is:
<html>
<head>
<title>Test</title>
</head>
<body>
<div style='-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;' unselectable='on'>
<a id="foo" onclick="toggle('foo')"> FOO </a>
<a id="bar" onclick="toggle('bar')"> BAR </a>
</div>
<script> {code above} </script>
</body>
</html>
This is live at http://jsfiddle.net/TF9X7/. Why doesn't this work in Chrome (or what mistake is Firefox forgiving me for)?
Or do it right, and use classes …
I'm very new to JavaScript; could you elaborate or provide a reference?
Instead of setting the style values directly via JS, you define them in your CSS, using a certain class name – and then you set or remove that class name for the elements:
CSS:
a { color: #BBBBBB; cursor: default; }
a.on { color: #42A6FF; cursor: pointer; }
a.on:hover { color: #444444; };
JS:
function turn_on(x) {
x.className = "on";
}
function turn_off(x) {
x.className = "";
}
http://jsfiddle.net/TF9X7/2/
I changed some parts of your script. Instead off window.onload, use body onload (<body onload="Init()">). The browser first needs to render the DOM in order to capture the objects.
In the function Init(), I changed to capture the element again, because Chrome is returning null, and I changed how you set the properties of style, the correct is object.style.property.
<script>
var foo = document.getElementById('foo');
var bar = document.getElementById('bar');
var foo_on = true;
function turn_on(x) {
x.style.color = "#42A6FF";
x.style.cursor = "pointer";
x.onmouseover = function () {
x.style.color = "#444444";
x.style.cursor = "pointer";
};
x.onmouseout = function () {
x.style.color = "#42A6FF";
x.style.cursor = "pointer";
};
}
function turn_off(x) {
x.style.color = "#BBBBBB";
x.style.cursor = "default";
x.onmouseover = null;
x.onmouseout = null;
}
function toggle(caller) {
if((foo_on && caller == 'bar') || (!foo_on && caller == 'foo')){
return;
}
if(foo_on){
turn_off(foo);
turn_on(bar);
}
else{
turn_on(foo);
turn_off(bar);
}
foo_on = !foo_on;
}
function init() {
foo = document.getElementById('foo');
bar = document.getElementById('bar');
foo_on = true;
turn_on(foo);
turn_off(bar);
}
body.onload = init();
</script>
But I advise you to use the way of CBroe

Categories