Toggle switch with JS - javascript

I'm trying to learn some JS, and would like to know if anyone could help me, please.
I would like to do, in a dashboard admin, an control with toggle switch to show on the index of the site whether the service is online or offline.
When on, put a "online" text in a green tag. And when not working, "offline" with a red tag.
How can I do this? With event listener? Thanks!
Example

Here's a simple exaple to show you an approach.
document.getElementById(`status`).addEventListener(`click`, function(){
const classes = this.classList;
if (classes.contains(`offline`)) {
this.textContent = `Online`;
classes.remove(`offline`);
classes.add(`online`);
} else if (classes.contains(`online`)) {
this.textContent = `Offline`;
classes.remove(`online`);
classes.add(`offline`);
}
});
#status {
color: white;
}
.online {
background: green;
}
.offline {
background: red;
}
<span id='status' class='offline'>Offline</span>

Related

Simplest way to toggle functionality in vanilla JS

Anyways I’m trying to make a lightbulb. It’s just a circle, I have an onclick event on a button, and the event function toggled a class, changing the color. But I want the text in the button to toggle as well when that class is activated.
I finally made it work as I was writing this question. But it still isn’t working how I want it. I only want to have one if statement.
I only want to solve it this specific way, by checking if a class is activated, and if yes, then change the text content of the button, if not, then leave it how it is.
let bulb = document.getElementById("light");
let lightSwitch = document.getElementById("switch");
function activity(event) {
bulb.classList.toggle("lightOn");
if (bulb.classList.contains("lightOn")) {
lightSwitch.textContent = "OFF";
} else if (bulb.classList.contains("lightOff")) {
lightSwitch.textContent = "ON";
}
}
.lightOn {
background: yellow;
}
<div id="light" class="lightOff"></div>
<button id="switch" onclick="activity()">ON</button>
How can I write it with only one if statement, Also, is there a way easier than this? Just vanilla not jQuery.
like this?
...
function activity(event) {
bulb.classList.toggle("lightOn");
lightSwitch.textContent = bulb.classList.contains("lightOn") ? "OFF" : "ON";
}
...
Your code can be simplified by extracting the bulb-specific default styles into a light class, then only toggle a new lightOn class. The default styles describe what to show if the bulb is off, but you can override those styles with !important in the lightOn class. Just like this:
let bulb = document.getElementById("light");
let lightSwitch = document.getElementById("switch");
lightSwitch.addEventListener('click', function() {
bulb.classList.toggle('lightOn');
lightSwitch.textContent = bulb.classList.contains("lightOn") ? "OFF" : "ON";
});
.light {
width: 100px;
height: 100px;
border-radius: 100%;
background: gray;
}
.lightOn {
background: yellow !important;
}
<div id="light" class="light"></div>
<button id="switch">ON</button>
You can also shorten your if-statement into a ternary expression, which is a better choice for this situation because only one value changes.

How to make Jquery Darkmode load directly on the beginning?

So I have set up a theme switcher on my site, which stores preference in localStorage and everything works fine. Except that my code is loaded after document.ready, and checks for condition / status of theme. I also tried removing document.ready, because obviously that would remove any finishing of loading the site, but that doesn't work, and the function starts direct on load and obviously can't change any CSS, because there isn't any. For now, I am using a preloader, which is working fine, but it would be awesome if it could work without it. I have also placed the code at the beginning of the body tag, so it should execute really early. In the following, I will show you my code and a screenshot of my console, where you can see when the code gets executed. For your knowledge, I am on Shopify, if that does anything.
Any help for making my theme / code switch faster, is very much appreciated.
My Console:
console img...
My Code (I am sorry for the formatting, I made if farly quickly in the Shopify admin, so no "Prettier" and also no "IntelliSense" :) )
// Darkmode #legoon #raffaelbaer
let ALLDARKMODE = '#over-header-info-bar-legoon, #StickyBar, .full-width--return-link,' +
'.cart__subtotal, .transcy-money, .site-footer__newsletter-input, #product-title__cart-page-legoon, .cart-table,' +
'.responsive-table__row, label, .gridforsubcategories_item-grid, .linkitem_hassubcategoriesinner, .sticky--active, .sticky--open,' +
'.icon-hamburger, .icon-close, .drawer__inner, #einloggendrawerlink, .drawer__nav-link--top-level, .einloggensvgmobile, .drawer__search,' +
'.drawer__search-input, #legooninstagrammobile, #instagramiconheadermobile, .svgdarkmode, .drawer__nav-item, .drawerforsocialicons, #footerlegoonlink,' +
'.content-block, .icon-arrow-down, .product-card__name, .product-card__info, .country-selector, .site-header__search-input, .menu-sub-custom1, .menu-sub-custom2,' +
'.labelcustomnav1, .labelcustomnav2, .labelcustomnav3, .labelcustomnav4, .menu-sub-custom3, .menu-sub-custom4, .nav-bar, h1, h2, #footer-down_copyright, h3, h4, h5,' +
'h6, body, a, input, textarea, select, .link-item>a , #instagramiconheader, .site-footer, .site-footer__copyright, .darkmodeswitch, p, .site-footer__newsletter-label>p,' +
'button, #icon-wunschliste, .page-container, .labelcustomnav1>p, .labelcustomnav2>p, .labelcustomnav3>p, .labelcustomnav4>p, .site-header, .legoonlogotop, .iconuserhead, .icon-cart,' +
'.notification--success, .notification--promo, .notification__message>span, .wg-drop.country-selector, .hr-empfy_cart-page';
$(document).ready(function() {
$('.darkmodeswitch').click(function() {
/*main toggle dark mode*/
$(ALLDARKMODE).toggleClass("dark");
/*change darkmode image on mobile drawer and desktop accordingly to current mode | theme (light or dark)*/
if ($(".darkmodeswitch").hasClass("dark")) {
document.getElementById('svgdarkmode').src = "https://cdn.shopify.com/s/files/1/0571/7137/8349/files/sun.svg?v=1650307091";
document.getElementById('svgdarkmodemobile').src = "https://cdn.shopify.com/s/files/1/0571/7137/8349/files/sun.svg?v=1650307091";
localStorage.setItem("theme", "dark");
} else {
document.getElementById('svgdarkmode').src = "https://cdn.shopify.com/s/files/1/0571/7137/8349/files/moon.svg?v=1650306791";
document.getElementById('svgdarkmodemobile').src = "https://cdn.shopify.com/s/files/1/0571/7137/8349/files/moon.svg?v=1650306791";
localStorage.setItem("theme", "light");
};
});
// Am Anfang
if (localStorage.getItem("theme") === "dark") {
console.log("Darkmode status = true");
$(ALLDARKMODE).addClass("dark");
} else {
console.log("Darkmode status = false");
$(ALLDARKMODE).removeClass("dark");
}
$('.darkmodeswitch').click();
});
For a dark mode switch, simply toggle a CSS class on the HTML element (document.documentElement.classList.toggle('dark');), and use that as a contextual selector for changes on your elements. Use CSS custom properties for the changes.
Here's an example of the approach. Please note that localStorage is unavailable in StackOverflow snippets due to security reasons, so I left that part out (you've got that working already anyway).
function toggleDarkMode() {
document.documentElement.classList.toggle('dark');
}
:root {
--body-bg-color: #fff;
--btn-bg-color: #f0f0f0;
--btn-fg-color: #333;
}
:root.dark {
--body-bg-color: #666;
--btn-bg-color: #333;
--btn-fg-color: #f0f0f0;
}
body {
background-color: var(--body-bg-color);
}
button {
background-color: var(--btn-bg-color);
border: 1px solid #888;
color: var(--btn-fg-color);
}
<button type="button" id="toggle" onclick="toggleDarkMode()">Dark Mode Button</button>

activate and deactivate in the same button

I am trying to make this button to do two things, I want it to be green and says "activate" and when I press it the button turns red and says "deactivate" and changes a column in the data to 1, and vice versa .
and if the column in the database is 1 it needs to be red and if it is 0 it needs to be green .
if someone just can tell what's the term so I can look for it because I searched a lot and I didn't come across what I need .
As mentioned in the comments by #yiffyiffyiff, the term you are looking for is called toggling. It sounds like you want to toggle the state of the button from active to deactive and vice-versa.
Using event delegation and classList.toggle.
document.addEventListener("click", handle);
function handle(evt) {
if (evt.target.classList.contains("toggleBtn")) {
return toggleBtn(evt.target);
}
}
function toggleBtn(btn) {
btn.classList.toggle("red");
/** ... more actions **/
}
.toggleBtn {
background-color: #B8F4B8;
border: none;
padding: 5px;
}
.toggleBtn:before {
content: "Activate";
}
.toggleBtn.red {
background-color: red;
color: white;
}
.toggleBtn.red:before {
content: "Deactivate";
}
<button class="toggleBtn"></button>

How to create a pre-choice selection?

I was interested in creating a temporary screen before a page where someone could choose an option that would determine what they're shown.
Example: Contact page where the screen asks "Are you interested in contacting us regarding a purchase or to talk to our customer team". Once they click an option it would display the corresponding contact form (one emails customer team, the other emails the purchase team).
I'm not sure how to code this as I'm new to HTML/CSS/JavaScript but based on what I've learned so far I'm assuming this is more advanced JavaScript.
I can provide a simple example to give you some sense about it, but I would suggest you to get more basic front end training first.
if (window.confirm('Do you want load form a?')) {
document.getElementById('a').style.display = 'block';
} else {
document.getElementById('b').style.display = 'block';
}
https://jsfiddle.net/8LmL4vdr/1/
I'm not entirely sure what you asking, but it sounds like if you changed the elements' z-index values on the click of the buttons, it would work.
You can read more about z-index here.
Or, you can use display.
Here is an example:
function layerPages(page) {
if (page == "one") {
document.getElementById("pageOne").style.display = "block"; // shows first page if that is what is called
} else if (page == "two") {
document.getElementById("pageTwo").style.display = "block"; // shows second page if that is what is called
} else {
window.alert("error, wrong useage");
}
document.getElementById("originalPage").style.display = "none"; // hides main page
}
document.getElementById("buttonOne").addEventListener("click", function
myfunction() {layerPages("one");}); // adds event listener that states that when the first button is clicked, the first page is shown and the original is hidden using the function "layerPages" (declared above)
document.getElementById("buttonTwo").addEventListener("click", function
myfunction() {layerPages("two");}); // adds event listener that states that when the second button is clicked, the second page is shown and the original is hidden using the function "layerPages" (declared above)
#originalPage {
background-color: black;
width: 100px;
height: 100px;
}
#pageOne, #pageTwo {
display: none; /*You need to make sure that both #pageOne and #pageTwo start out as display: none;*/
background-color: yellow;
width: 100px;
height: 100px;
}
#pageTwo {
background-color: orange;
}
<div id="originalPage">
<button id="buttonOne">Page One</button>
<button id="buttonTwo">Page Two</button>
</div>
<div id="pageOne"></div>
<div id="pageTwo"></div>
<!--The content goes into each div, I'm sure that you can figure that out-->

Watermark for contenteditable div element

I have "contenteditable" div element. I want to set a watermark for it so that when user tries to write something in the div the watermark should go disappear.
I tried some watermark jQuery plugins, all work for input, textarea. What is the way to implement this feature for contenteditable div?
If you by "watermark" mean like a placeholder effect, the concept should be fairly simple:
var mark = 'Watermark',
edited = false;
$('[contenteditable]').focus(function() {
if(!edited) {
$(this).empty();
}
}).blur(function() {
if(!$(this).html()) {
$(this).html(mark);
}
}).keyup(function() {
edited = true;
}).text(mark);
Demo: http://jsfiddle.net/jjxvR/1/
Here's my answer to another question:
It uses a combination of jQuery and CSS3. Works exactly like the html5 placeholder attribute!.
Hides itself right away when you input the first letter
Shows itself again when you delete what you input into it
HTML:
<div class="placeholder" contenteditable="true"></div>
CSS3:
.placeholder:after {
content: "Your placeholder"; /* this is where you assign the place holder */
position: absolute;
top: 10px;
color: #a9a9a9;
}
jQuery:
$('.placeholder').on('input', function(){
if ($(this).text().length > 0) {
$(this).removeClass('placeholder');
} else {
$(this).addClass('placeholder');
}
});
DEMO: http://jsfiddle.net/Tomer123/D78X7/
I solved it this way:
div[contenteditable]:empty:before {
content: '-';
}
div[contenteditable]:focus:before {
color: transparent;
}

Categories

Resources