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/
Related
I have got a code for changing the header when search button gets pressed, this part of it works.
function searchButtonAction() {
if (isSubmit()) {
document.getElementById('search-box').submit();
} else {
showSearch();
noShowMenuLogo();
function clf() {
if (!searchInProgress) {
noShowSearch(); showMenuLogo();
} else {
setTimeout(clf, 25)
}
}
sia = setInterval(() => {
if (searchInProgress) {
clearInterval(sia);
setTimeout(clf, 25);
}
}, 25);
}
}
However for some reason when I do this,
function noShowSearch() {
document.getElementById('search-text').style.display = 'none';
document.getElementById('search-text').style.width = '';
document.getElementById('clear-search').style.display = 'none';
document.getElementById('search-box').style.backgroundColor = 'none';
document.getElementById('search-box').style.border = 'none';
document.getElementById('search-box').style.width = '';
document.getElementById('left-items-box').style.width = '';
}
search-box's background-color doesn't change
the result i want:
the result i get:
The solution is at the comments.
background-color: none; is an invalid property value. Maybe use: document.getElementById('search-box').style.backgroundColor = 'transparent';
I want to make a button for night and day mode.I found this link but it doesn't work for me.
when i click the button, it applies css to change background and text color and button value which is night to day but if i click button again it doesn't work. it keeps execute "if" part not "else" part.
//nightmode
var mode = localStorage.getItem("mode");
if (mode != null) {
document.getElementById("body").classList.add(mode);
}
document.getElementById("nightButton").onclick = function() {
var nightButton = document.getElementById("nightButton")
var body = document.getElementById("body");
if (nightButton.value = "night") {
body.classList.add("nightMode");
nightButton.value = "day";
localStorage.setItem('mode', 'nightMode');
} else {
body.classList.remove("nightMode");
nightButton.value = "night";
localStorage.setItem("mode", null);
}
};
.nightMode {
background-color: black;
color: white;
}
<body id="body">
<input type="button" value="night" id="nightButton">
<div>abcd</div>
</body>
Just change the line
if (nightButton.value = "night") {
to
if (nightButton.value == "night") {
You can simplify the mode button handler. This snippet including handling of localStorage (can't be used in SO-snippets) can be found #JsFiddle
document.addEventListener("click", evt => {
if (evt.target.id === "nightButton") {
const body = document.body;
body.classList.toggle("nightMode");
evt.target.value = `set ${
body.classList.contains("nightMode") ? "day" : "night"}`;
document.querySelector("#currentMode").textContent = `Current mode: ${
body.classList.contains("nightMode") ? "NIGHT" : "DAY"}`;
}
});
.nightMode {
background-color: black;
color: white;
}
body {
margin: 2rem;
}
#currentMode {
margin-top: 1rem;
}
<div>abcd
<input type="button" value="set night" id="nightButton">
</div>
<div id="currentMode"></div>
there is a little error in your code.
This code: if (nightButton.value = "night") {
Can you change it: if (nightButton.value == "night") {
Example here: https://codepen.io/yasgo/pen/OJRLErL
thank you all
I don't know if this is good codes but i tried this and it works ...
var mode = localStorage.getItem("mode");
document.getElementById("body").classList.add(mode);
if (mode == "nightMode") {
document.getElementById("nightButton").value = "day"
} else {
document.getElementById("nightButton").value = "night"
}
document.getElementById("nightButton").onclick = function () {
var nightButton = document.getElementById("nightButton")
var body = document.getElementById("body");
if (nightButton.value == "night") {
body.classList.add("nightMode");
nightButton.value = "day";
localStorage.setItem('mode', 'nightMode');
} else {
body.classList.remove("nightMode");
nightButton.value = "night";
localStorage.setItem("mode", "daymode");
}
};
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.
I was wondering how it is possible to make the button undo something too after clicking it. In my scenario just simple formatting of Text(Color,size etc), when you first click it, it formats the text as described in Javascript, but I would like to add a function, that when you click it again, that it undoes that.
`<script>
function myFunction(){
document.getElementById("demo").style.fontsize="25px";
document.getElementById("demo").style.color="#3AF702";
document.getElementById("demo").style.backgroundcolor="red";
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
I checked other articles already, which seemed to be related, but I did not get any smarter out of those, so my apologies in advance if it is a dup and thanks for your help!
<script>
var flag = true;
function myFunction(){
let el = document.getElementById("demo");
el.style.fontsize = flag ? "25px" : "";
el.style.color= flag ? "#3AF702" : "";
el.style.backgroundcolor=flag ? "red" : "";
flag = !flag;
}
</script>`
<button type="change" onclick="myFunction()">Change!</button>
The easiest way to do this is to add and remove a class
<style>
.change {
font-size: 25px;
color: #3AF702;
background-color="red"
}
</style>
<script>
var x = 0;
function myFunction() {
if (x == 0) {
document.getElementById("demo").classList.add("change");
x = 1;
} else {
document.getElementById("demo").classList.remove("change");
x = 0;
}
}
</script>
<button type="change" onclick="myFunction()">Change!</button>
Create an object that stores the initial values of your button and a variable which holds the state of it.
var state = 0;
var backup = {};
backup.fontSize = document.getElementById("demo").style.fontsize;
backup.color = document.getElementById("demo").style.color;
backup.background = document.getElementById("demo").style.backgroundcolor;
Now you can easily switch between the backup and the new values like this:
function myFunction() {
if (state == 0) {
document.getElementById("demo").style.fontsize = "25px";
document.getElementById("demo").style.color = "#3AF702";
document.getElementById("demo").style.backgroundcolor = "red";
state = 1;
} else {
document.getElementById("demo").style.fontsize = backup.fontSize;
document.getElementById("demo").style.color = backup.color;
document.getElementById("demo").style.backgroundcolor = backup.background;
state = 0;
}
}
var flag = true;
function myFunction(){
var x = document.getElementById("demo");
if (flag) {
x.style.backgroundColor = "red";
x.style.color="#3AF702";
x.style.fontSize="25px"
} else {
x.style.backgroundColor = "blue";
x.style.color="#dddddd";
x.style.fontSize="10px"
}
flag = !flag
}
function myFunction(){
demo.className = demo.className ? "" : "style"
}
.style {
font-size: 25px;
color: red;
background: blue;
}
<p id="demo">Hi!</p>
<button type="change" onclick="myFunction()">Change!</button>
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';
}
}