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';
Related
i have a Div holding an image with the id sunset that i want to add an onclick to to change its width from the CSS 25% to 100%
cannot see why my code is not working
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click) {
content.style.width = "100%";
}
else {
content.style.width = "25%";
}
});
CSS
#sunset{
width:25%
}
The first if statement doesn't check if the first_click var is true (assuming that is what you intend to do). Since it is empty it would return false and the else statement would run, keeping your image at 25%.
try this:
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click == true) {
content.style.width = "100%";
}
else {
content.style.width = "25%";
}
});
Have you tried adding height to your container ? This should work
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click) {
content.style.width = "100%";
first_click = false;
}
else {
content.style.width = "25%";
}
});
#sunset{
width:25%;
background: #000;
height: 200px;
}
<div id="sunset"></div>
The problem is that you're not toggling the first_click variable to true or false when the image is clicked. The code below fixes this by setting first_click = !first_click:
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function() {
if (first_click) {
content.style.width = "100%";
} else {
content.style.width = "25%";
}
first_click = !first_click;
});
#sunset {
width: 25%
}
<img id="sunset" src="https://dummyimage.com/150/f8f">
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 am trying to make a variable increase every second. What should I include inside the function autoClicker, so that the variable clicks increase by 1 every second? Also, if there are any more problems in the code, could you point them out to me? Sorry if this question seems basic, I am still quite new to JavaScript.
// The variable we are trying to increase
var clicks = 0;
var upgrade1 = 1;
function getClicks() {
clicks += upgrade1;
document.getElementById("clicks").innerHTML = clicks;
};
function buyAutoClicker() {
if (clicks >= 50) {
clicks -= 50
autoClicker()
} else {
alert = "Sorry, you don't have enough clicks to buy this";
}
}
// The function I will use to increase clicks
function autoClicker() {}
You could create an AutoClicker class that has a start, pause, ad update function. It will be in charge of managing the setInterval id.
Edit: I updated it to include upgrade buttons and the target can now be manually clicked.
const upgrades = [{
cost: 50,
rate: 2
}, {
cost: 100,
rate: 4
}];
const main = () => {
const target = document.querySelector('.auto-clicker');
const span = document.querySelector('.info > span');
const btn = document.querySelector('.btn-toggle');
const clicker = new AutoClicker(target, 1000, (clicks) => {
span.textContent = clicks;
}).start();
initializeUpgrades(clicker, upgrades);
btn.addEventListener('click', (e) => {
e.target.textContent = clicker.isRunning() ? 'Start' : 'Pause';
clicker.toggle();
});
};
const initializeUpgrades = (clicker, upgrades) => {
const upgradeContainer = document.querySelector('.upgrades');
upgrades.forEach(upgrade => {
const btn = document.createElement('button');
btn.textContent = upgrade.cost;
btn.value = upgrade.rate;
btn.addEventListener('click', (e) => {
let cost = parseInt(e.target.textContent, 10);
let value = parseInt(e.target.value, 10);
if (clicker.clicks >= cost) {
clicker.clicks -= cost;
clicker.step = value
} else {
console.log(`Cannot afford the ${value} click upgrade, it costs ${cost} clicks`);
}
});
upgradeContainer.appendChild(btn);
});
};
class AutoClicker {
constructor(target, rate, callback) {
if (typeof target === 'string') {
target = document.querySelector(target);
}
this.target = target;
this.rate = rate;
this.callback = callback;
this.init();
}
init() {
this.step = 1;
this.clicks = 0;
this._loopId = null;
this.target.addEventListener('click', (e) => {
this.update();
});
}
isRunning() {
return this._loopId != null;
}
toggle() {
this.isRunning() ? this.pause() : this.start();
}
update() {
this.clicks += this.step;
if (this.callback) {
this.callback(this.clicks);
}
}
start() {
this.update(); // Update immediately
this._loopId = setInterval(() => this.update(), this.rate);
return this;
}
pause() {
clearInterval(this._loopId);
this._loopId = null;
return this;
}
}
main();
.wrapper {
width: 10em;
text-align: center;
border: thin solid grey;
padding: 0.5em;
}
.auto-clicker {
width: 4em;
height: 4em;
background: #F00;
border: none;
border-radius: 2em;
}
.auto-clicker:focus {
outline: none;
}
.auto-clicker:hover {
background: #F44;
cursor: pointer;
}
.info {
margin: 1em 0;
}
.upgrades {
display: inline-block;
}
.upgrades button {
margin-right: 0.25em;
}
<div class="wrapper">
<button class="auto-clicker"></button>
<div class="info">Clicks: <span class="clicks"></span></div>
<button class="btn-toggle">Pause</button>
<div class="upgrades"></div>
</div>
// The variable we are trying to increase
var clicks = 0;
var upgrade1 = 1;
function getClicks() {
clicks += upgrade1;
document.getElementById("clicks").innerHTML = clicks;
};
function buyAutoClicker() {
if (clicks >= 50) {
clicks -= 50
autoClicker()
} else {
alert = "Sorry, you don't have enough clicks to buy this";
}
}
// The function I will use to increase clicks
setInterval(function(){ clicks++;console.log(clicks); }, 1000);
Use setInterval to run a function at a specified interval. This will run increaseClicks every 1000 milliseconds (every second):
function increaseClicks() {
clicks++;
}
var interval = setInterval(increaseClicks, 1000);
Use clearInterval to stop running it:
clearInterval(interval);
You can omit var interval = if you don't want to use clearInterval:
setInterval(increaseClicks, 1000);
There might be several things to improve this code
the use of textContent is preferable to innerHTML, it checks if there are no html tags in the text
then using inline functions like ()=>{} are more useful but in this program it does'nt make a difference, where you to use it in object oriented context you could use it several ways
you don't need document.getElementById, you could just use id.
And finaly (this is just à random tip which has nothing to do with much of anything) you may consider branchless programming because ifs are expensive.
Stackoverflow Branchless Programming Benefits
But anyways you should have fun :)
var clicks = 0;
var upgrade1 = 1;
function getClicks() {
clk.textContent = (clicks += upgrade1);
};
function buyAutoClicker() {
if (clicks >= 50) {
clicks -= 50
setInterval(()=>{getClicks();},1000);
} else {
alert("Sorry, you don't have enough clicks to buy this");
}
}
clk.onclick=()=>{getClicks();};
b.onclick=()=>{buyAutoClicker();};
html,body{height:100%;width:100%;margin:0;}
p{height:50px;width:50px;background:red;}
<p id="clk"></p>
<p id="b"></p>
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.
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/