When selecting "A&L" in the select, the radio group is hidden and its value is set to "n".
I try to trigger the change event so that the "Hello"-div disappears too, but it doesn't work correctly - on debugging I noticed that the change event is executed twice - the first time correctly and then again with the value "j".
What's my mistake?
Here's the full code: https://jsfiddle.net/95Lxroqy/
After I looked through some other questions it seemed to me that .val(['n']).change(); (line 24) should have worked -
but it seems like I'm still missing something.
// find elements
var banner = $("#banner-message");
var button = $("#place");
var langs = $("#langs");
var trans = $("#trans");
var radioGroup = $("input[type=radio][name=translate]");
var div = $("#dynamic");
radioGroup.change(function() {
if (this.value === 'n') {
div.hide();
}
else if (this.value === 'j') {
div.show();
}
});
// handle click and add class
button.change(function(event){
var al = button.val() === "al";
if(al){
langs.show();
trans.hide();
radioGroup.val(['n']).change();
}else{
trans.show();
langs.hide();
}
}).change();
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<select id="place">
<option value="in">Internal</option>
<option value="al">A&L</option>
</select>
<select id="langs">
<option value="volvo">German</option>
<option value="saab">English</option>
</select>
<fieldset id="trans">
<input type="radio" id="n" name="translate" value="n">
<label for="n"> Nein</label>
<input type="radio" id="j" name="translate" value="j">
<label for="j"> Ja</label>
</fieldset>
<div id="dynamic">
Hello
</div>
</div>
val() get/set the value of the element. Your code matches all the options exist in the collection variable, it does not match the specific element you are looking for. You can target the parent element from which you can find the the specific element by using attribute selector.
Try
radioGroup.parent().find('[value=n]').change();
Update: The more feasible solution is using the filter()
radioGroup.filter('[value=n]').change();
Related
I've got a few divs, and it's a dashboard kinda website so I need to update it everyday.
I can manually edit the HTML and all but that's you know...inefficient.
Each div has a ul element in it, and everyday I need to add a few li elements.
I've tried a JavaScript function that appends li elements and I'll add it in the code snippet too. But still, it's kinda temporary because if I delete that line of code in my js file the added li element will also disappear. So I'm looking for a way to append li elements to an unordered list permanently, and it would be nice to have a way to delete them too when they get really old.
function append(ul, data) {
try {
ul.appendChild(document.createElement("li")).innerHTML = data;
} catch (e) {
console.error(e);
console.log("error boi");
}
}
append(document.getElementById("ul-1"), "door")
div {
background-color: cyan;
height: 300px;
width: 500px;
}
<div id="1">
div 1
<br />
<ul id="ul-1">
<li>reeeeeeeee</li>
<li>ramen ramen ramen ramen</li>
<li>..........................</li>
<!-- have to append few li items every day-->
</ul>
</div>
<br>
<div id="2">
div 2
<br />
<ul id="ul-2">
<li>ok</li>
<li>ravioli ravioli ravioli ravioli</li>
<li>..........................</li>
</ul>
</div>
Note ↓:
This piece of code just shows an example of how you can add or remove items easily from and to the lists!
As #Chris G and #L.K. Kabilan mentioned, to store data you either need a Database or in the Local Storage. However, by storing data in the Local Storage you're taking a risk of losing the data because it's stored only in the browser.
// Get the elements
var input = document.getElementById('input');
var btn = document.getElementById('btn');
var select = document.getElementById('select');
var selected = select.options[select.selectedIndex].value;
// Delete the item of the clicked 'X' icon
function delLi(){
var del = document.querySelectorAll('li span');
for (var i = 0; i < del.length; i++){
del[i].addEventListener('click', (e) => {
e.target.parentElement.remove();
});
}
}
// Get the selected option
select.addEventListener('change', () => {
selected = select.options[select.selectedIndex].value;
});
// Wrap the input value in an item and append it to the selected list
btn.addEventListener('click', (e) => {
var val = input.value;
if(val == '' || val.length <= 0){
e.preventDefault();
} else {
var li = `<li><span>×</span><p>${val}</p></li>`;
document.getElementById(selected).innerHTML += li;
delLi();
}
});
delLi();
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.wrapper {
background-color: aqua;
width: 500px;
margin: 50px auto;
border-radius: 5px;
padding: 10px;
}
ul {
list-style-type: none;
line-height: 1.5;
}
ul::before {
content: attr(aria-label);
font-weight: bold;
font-size: 20px;
}
li {
display: flex;
align-items: center;
}
li span {
font-size: 18px;
font-weight: bold;
margin-right: 10px;
cursor: pointer;
}
form {
margin: 0 auto;
width: 500px;
background-color: rgb(233, 208, 17);
padding: 10px;
}
#input {
height: 30px;
width: 100%;
border-radius: 5px;
border: none;
padding: 0 10px;
display: block;
margin-bottom: 10px;
}
#btn {
width: 100px;
height: 34px;
background-color: green;
color: white;
border: none;
border-radius: 5px;
display: inline-block;
cursor: pointer;
}
<main>
<div class="wrapper" id="wrapper-1">
<ul id="ul-1" aria-label="List 1">
<li><span>×</span><p>Item 1</p></li>
<li><span>×</span><p>Item 2</p></li>
<li><span>×</span><p>Item 3</p></li>
<li><span>×</span><p>Item 4</p></li>
</ul>
</div>
<div class="wrapper" id="wrapper-2">
<ul id="ul-2" aria-label="List 2">
<li><span>×</span><p>Item 1</p></li>
<li><span>×</span><p>Item 2</p></li>
</ul>
</div>
<form action="">
<input id="input" type="text">
<select name="" id="select">
<option value="ul-1">List 1</option>
<option value="ul-2">List 2</option>
</select>
<input id="btn" type="button" value="Submit">
</form>
</main>
I guess u can use a JSON file to store and retrieve data, or u can go for PHP to get & retrieve data, yet u will be needing a Database, if I'm not wrong, using JSON would be more efficient.(If I'm wrong correct me)
check this link below https://www.w3schools.com/whatis/whatis_json.asp#:~:text=JSON%20stands%20for%20JavaScript%20Object,describing%22%20and%20easy%20to%20understand
Hope this answer helped u.
I have the following code
var inter = [];
const changeColor = (evt) => {
if (evt.currentTarget.classList.contains("is-active")) {
evt.currentTarget.classList.remove("is-active");
} else {
evt.currentTarget.classList.add("is-active");
var elements = document.getElementsByClassName('is-active');
inter = [];
for (var i = 0; i < elements.length; i++) {
inter.push(elements[i].innerHTML)
}
alert(inter);
}
};
const EL_tagger1010_children = document.querySelectorAll(".tagger1010 span");
EL_tagger1010_children.forEach(EL => EL.addEventListener("click", changeColor));
.tagger1010 span {
padding: 6px 10px;
background: #D0E8E4;
border-radius: 18px;
color: #000000;
font-family: Roboto;
font-size: 12px;
margin: 0 4px 8px 0;
font-weight: 500;
display: inline-block;
word-wrap: break-word;
white-space: normal;
cursor: pointer;
user-select: none;
border: 1px solid BBD0CD;
}
.tagger1010 span.is-active {
background-color: #008fde;
color: #ffffff;
}
.tagger1010 span:hover {
background-color: #008fde;
color: #ffffff;
}
<div class="tagger1010">
<span>Google</span>
<span>Microsoft</span>
<span>Facebook</span>
<span>LinkedIn</span>
</div>
<div class="as-console-wrapper"></div>
<div class="as-console"></div>
<div class="as-console-wrapper">
<div class="as-console">
</div>
</div>
This code does what I want it to do for now, but I would like to create an element that has an id that stores the value of the "inter" array in the following code. I have never before seen an instance where a single variable has an id that can be referenced elsewhere. So I was wondering if I can put the value of the "inter" array in a div element, or if I can just assign an id to the inter array itself?
Try using the DOM id feature:
document.getElementById("demo").id = "newid";
Reference:
https://www.w3schools.com/jsref/prop_html_id.asp
You cannot assign the id of an HTML node to a JS array, but you can put the contents of an array in to a div and assign an id to that div. You can create the div on the fly in the JS code, or put it directly into your HTML and just fill in the array values and assign the id. Following an example of how to create a div in JavaScript, set an id on it and put the array values into it one by one:
var arr = ["some", "array", "values"];
div = document.createElement("div"); // create a new div
div.id = "someid"; // set the id of the div
for (var item of arr) {
div.innerHTML += "<p>" + item + "</p>"; // put each array item into a separate paragraph in the div
}
document.body.appendChild(div); // append the div with the paragraphs to the document body
#someid {
background-color: yellow;
}
<body>
<p>The array values are displayed below.</p>
</body>
Giving you another option of just using radio button list to render the selectable list. To get the selection, you just read the form field value.
[name="rb-site"] {
display: none;
}
[name="rb-site"] label {
padding: 6px 10px;
background: #D0E8E4;
border-radius: 18px;
color: #000000;
font-family: Roboto;
font-size: 12px;
margin: 0 4px 8px 0;
font-weight: 500;
display: inline-block;
word-wrap: break-word;
white-space: normal;
cursor: pointer;
user-select: none;
border: 1px solid BBD0CD;
}
[name="rb-site"]:checked + label {
background-color: #008fde;
color: #ffffff;
}
[name="rb-site"] + label:hover {
background-color: #008fde;
color: #ffffff;
}
<div class="tagger1010">
<input type="radio" value="google" id="rb-google" name="rb-site">
<label for="rb-google">Google</label>
<input type="radio" value="microsoft" id="rb-microsoft" name="rb-site">
<label for="rb-microsoft">Microsoft</label>
<input type="radio" value="Facebook" id="rb-facebook" name="rb-site">
<label for="rb-facebook">Facebook</label>
<input type="radio" value="LinkedIn" id="rb-linkedin" name="rb-site">
<label for="rb-linkedin">LinkedIn</label>
</div>
So when you want to get the selected radio button and read the variable.
document.querySelctor('name="rb-site"]:checked').value
It is more HTML, but less JavaScript.
I have a drop down menu I need to make appear and disappear using pure JavaScript (no libraries/jQuery). Thus I am developing a toggle function. However despite trying several approaches, nothing seems to work. My current idea is to create a variable to hold the state of the menu (open or closed). Once the display of the menu changes from "none" to "block", the variable should change from "closed" to "open". Then an event listener would be added to the body element so when anything is clicked, the menu closes (i.e. the display property is changed back to "none").
Unfortunately the above doesn't seem work. When I put the If/else block outside of an event listener it fires when the page loads, but not when the menuToggle variable changes. If I put it or a function inside the menuPlaceholder event listener the menu won't open, probably due to the open and close code being called basically at the same time.
Clearly I am missing something, probably related to program control or function calling. Does anyone have any insights?
The code I am working with is below. Note the alert functions peppered throughout the code are for testing purposes only.
//Puts IDs for search preference selection box into variables
var menuPlaceholder = document.getElementById('searchSelection');
var menuDisplay = document.getElementById('searchOptions');
var boxLabel = document.getElementById('searchLabel');
//Puts IDs for text input box and submission into variables
var searchBoxPlaceholder = document.getElementById('searchInput');
var searchInput = document.getElementById('searchBox');
var submitButton = document.getElementById('submit');
//Adds class to each search option and puts ID of hidde field into variable
var searchPrefSubmission = document.getElementsByClassName('buttonSearch');
var hiddenInput = document.getElementById('searchChoice');
//Global variable to indicate whether searchOptions menu is opened or closed
var menuToggle = "closed";
//Closes element when one clicks outside of it.
function hideOnClickOutside(element) {
const outsideClickListener = event => {
if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
element.style.display = 'none'
removeClickListener()
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener)
}
document.addEventListener('click', outsideClickListener)
}
const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length )
//When the placeholder box is clicked, the option menu appears
menuPlaceholder.addEventListener('click', function (event){
menuDisplay.style.display = "block";
menuToggle = "open";
//Add click event to searchPref buttons
for (i = 0; i < searchPrefSubmission.length; i++) {
//Assigns value of the button to both the hidden input field and the placeholder box
searchPrefSubmission[i].addEventListener('click', function(event) {
hiddenInput.value=this.value;
boxLabel.innerHTML = this.value;
menuDisplay.style.display = "none";
menuPlaceholder.style.display = "inline-block";
});
}
});
//This code causes the text input box of the search form to appear when the background box is clicked
searchBoxPlaceholder.addEventListener('click', function(event){
searchInput.style.display = "inline";
submitButton.style.display = "inline";
//hideOnClickOutside(menuDisplay);
});
if (menuToggle == "open"){
document.body.addEventListener('click', function(event){
alert('Foo!');
})
}else{
alert('Boo!');
}
/*function toggleMenu () {
//menuDisplay.style.display = "none";
alert('Boo!');
menuToggle = "closed";
}*/
body {
font-family:Montserrat, sans-serif;
}
#searchOptionPlaceholder {
display: inline-block;
}
#searchSelection {
padding: 10px 20px;
margin-right: 10px;
background-color: #F0F3F5;
display: inline-block;
color: #000000;
width: 140px;
max-width: 200px;
max-height: 35px;
border: 2px solid black;
vertical-align: middle;
}
#searchSelection img {
float: right;
}
#searchLabel {
display: inline-block;
padding-top: 10px;
vertical-align: top;
}
#searchOptions {
display: none;
background-color: #F0F3F5;
position: absolute;
z-index: 2;
}
#searchOptions ul {
background-color: #F0F3F5;
padding: 5px;
}
#searchOptions li {
list-style-type: none;
border-bottom: 2px solid black;
}
#searchOptions li:hover {
background-color: #706868;
color: #ffffff;
}
.buttonSearch {
background-color: transparent;
border: none;
padding: 10px;
font-size: 14px;
}
.searchSubHeading {
font-size: 12px;
}
#searchInput {
display: inline-block;
background-color: #F0F3F5;
padding: 10px 100px;
position: relative;
top: 0px;
max-width: 350px;
border: 2px solid black;
vertical-align: middle;
}
#searchInput img {
position: relative;
left: 80px;
}
#searchBox {
display: none;
width: 80%;
background-color: #F0F3F5;
border: none;
font-size: 1.5em;
position: relative;
right: 50px;
vertical-align: middle;
}
#submit {
border: none;
background-image: url('https://library.domains.skidmore.edu/search/magnifyingGlass.png');
background-repeat: no-repeat;
background-size: contain;
width: 50px;
height: 30px;
position: relative;
right: -80px;
vertical-align: middle;
}
#otherLinks {
margin-top: 10px;
}
#otherLinks a{
color: #000000;
}
#otherLinks a:hover{
color: #006a52;
}
<h1>Library Search</h1>
<form method="post" action="https://library.domains.skidmore.edu/search/searchBox.php" id="librarySearch">
<div id="searchSelection"><span id="searchLabel">Catalog</span><img src="down.png" height="30px" width="30px" /></div>
<div id="searchOptions">
<ul>
<li><button type="button" name="searchPref" value="Catalog" class="buttonSearch">Catalog<br /><br /><span class="searchSubHeading">Search books and DVDs</span></button></li>
<li><button type="button" name="searchPref" value="SearchMore" class="buttonSearch">SearchMore<br /><br /><span class="searchSubHeading">Search everything</span></button></li>
<li><button type="button" name="searchPref" value="Journals" class="buttonSearch">Journals<br /><br /><span class="searchSubHeading">Search journals</span></button></li>
</ul>
</div>
<div id="searchInput">
<input type="hidden" id="searchChoice" name="searchPref" value="catalog" />
<input type="search" id="searchBox" size="60" name="searchText" placeholder="Search our holdings"/><button type="submit" id="submit"></button></div>
<div id="otherLinks">Advanced Catalog Search | WorldCat | eBooks</div>
</form>
Some issues:
Adding event listeners within an event listener is in most cases a code smell: this will add those inner listeners each time the outer event is triggered. Those listeners remain attached, and so they accumulate. So, attach all event handlers in the top-level script, i.e. on page load, and then never again.
The if ... else at the end will execute on page load, and then never again. So the value of menuToggle is guaranteed to be "closed". You need to put that if...else switch inside the handler, so that it executes every time the event triggers, at which time the menuToggle variable will possibly have a modified value.
The body element does not stretch (by default) over the whole window. If you want to detect a click anywhere on the page, you should attach the listener on the document element itself, not on document.body.
When the click on the menu placeholder is handled, you should avoid that this event "bubbles" up the DOM tree up to the document, because there you have the other handler that wants to hide the menu again. You can do this with event.stopPropagation().
The global variable is not absolutely necessary, but if you use it, then I would call it menuVisible and give it a boolean value: false at first, and possibly true later.
For actually toggling the menu, I would create a function, which takes the desired visibility (false or true) as argument, and then performs the toggle.
Do not use undeclared variables, like the for loop variable i. Define it with let.
Here is your code with those changes implemented. Of course, there is still a lot that could be improved, but I believe that goes beyond the scope of this question:
var menuPlaceholder = document.getElementById('searchSelection');
var menuDisplay = document.getElementById('searchOptions');
var boxLabel = document.getElementById('searchLabel');
var searchBoxPlaceholder = document.getElementById('searchInput');
var searchInput = document.getElementById('searchBox');
var submitButton = document.getElementById('submit');
var searchPrefSubmission = document.getElementsByClassName('buttonSearch');
var hiddenInput = document.getElementById('searchChoice');
// Changed name and type of global variable:
var menuVisible = false;
// Removed some functions ...
menuPlaceholder.addEventListener('click', function (event){
// Use new function for actually setting the visibility
toggleMenu(!menuVisible);
// Avoid that click event bubbles up to the document level
event.stopPropagation();
});
// Add these event handlers on page load, not within another handler
// Define loop variable with let
for (let i = 0; i < searchPrefSubmission.length; i++) {
//Assigns value of the button to both the hidden input field and the placeholder box
searchPrefSubmission[i].addEventListener('click', function(event) {
hiddenInput.value = this.value;
boxLabel.innerHTML = this.value;
// Use the new function for setting the visibility
toggleMenu(false);
menuPlaceholder.style.display = "inline-block";
});
}
searchBoxPlaceholder.addEventListener('click', function(event){
searchInput.style.display = "inline";
submitButton.style.display = "inline";
});
// Bind handler on document itself, and call new function
document.addEventListener('click', function(event) {
toggleMenu(false);
});
// new function to perform the toggle
function toggleMenu(show) {
menuDisplay.style.display = show ? "block" : "none";
menuVisible = show;
}
body {
font-family:Montserrat, sans-serif;
}
#searchOptionPlaceholder {
display: inline-block;
}
#searchSelection {
padding: 10px 20px;
margin-right: 10px;
background-color: #F0F3F5;
display: inline-block;
color: #000000;
width: 140px;
max-width: 200px;
max-height: 35px;
border: 2px solid black;
vertical-align: middle;
}
#searchSelection img {
float: right;
}
#searchLabel {
display: inline-block;
padding-top: 10px;
vertical-align: top;
}
#searchOptions {
display: none;
background-color: #F0F3F5;
position: absolute;
z-index: 2;
}
#searchOptions ul {
background-color: #F0F3F5;
padding: 5px;
}
#searchOptions li {
list-style-type: none;
border-bottom: 2px solid black;
}
#searchOptions li:hover {
background-color: #706868;
color: #ffffff;
}
.buttonSearch {
background-color: transparent;
border: none;
padding: 10px;
font-size: 14px;
}
.searchSubHeading {
font-size: 12px;
}
#searchInput {
display: inline-block;
background-color: #F0F3F5;
padding: 10px 100px;
position: relative;
top: 0px;
max-width: 350px;
border: 2px solid black;
vertical-align: middle;
}
#searchInput img {
position: relative;
left: 80px;
}
#searchBox {
display: none;
width: 80%;
background-color: #F0F3F5;
border: none;
font-size: 1.5em;
position: relative;
right: 50px;
vertical-align: middle;
}
#submit {
border: none;
background-image: url('https://library.domains.skidmore.edu/search/magnifyingGlass.png');
background-repeat: no-repeat;
background-size: contain;
width: 50px;
height: 30px;
position: relative;
right: -80px;
vertical-align: middle;
}
#otherLinks {
margin-top: 10px;
}
#otherLinks a{
color: #000000;
}
#otherLinks a:hover{
color: #006a52;
}
<h1>Library Search</h1>
<form method="post" action="https://library.domains.skidmore.edu/search/searchBox.php" id="librarySearch">
<div id="searchSelection">
<span id="searchLabel">Catalog</span>
<img src="down.png" height="30px" width="30px" />
</div>
<div id="searchOptions">
<ul>
<li>
<button type="button" name="searchPref" value="Catalog" class="buttonSearch">
Catalog<br /><br /><span class="searchSubHeading">Search books and DVDs</span>
</button>
</li>
<li>
<button type="button" name="searchPref" value="SearchMore" class="buttonSearch">
SearchMore<br /><br /><span class="searchSubHeading">Search everything</span>
</button>
</li>
<li>
<button type="button" name="searchPref" value="Journals" class="buttonSearch">
Journals<br /><br /><span class="searchSubHeading">Search journals</span>
</button>
</li>
</ul>
</div>
<div id="searchInput">
<input type="hidden" id="searchChoice" name="searchPref" value="catalog" />
<input type="search" id="searchBox" size="60" name="searchText" placeholder="Search our holdings"/>
<button type="submit" id="submit"></button>
</div>
<div id="otherLinks">
Advanced Catalog Search |
WorldCat |
eBooks
</div>
</form>
I have a custom switch in CSS that I am using in a template for django. I am loading the javascript file properly but when I go to use the switch I don't get the expected result. The expected result is that the background would change colour this does not work using the switch. I added a button into the template to see if the button would work which it did,
javascript file:
function darkModen() {
var element = document.body;
element.classList.toggle("dark-mode");
}
HTML switch this does nothing:
<div class="onoffswitch" style="position: fixed;left: 90%;top: 4%;" onclick="darkMode()">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" onclick="darkMode">
<label class="onoffswitch-label" for="myonoffswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
HTML button that does do what is expected.
<button onclick="darkMode()">Toggle dark mode</button>
CCS if this is causing the problem:
.onoffswitch {
position: relative; width: 90px;
-webkit-user-select:none; -moz-user-select:none; -ms-user-select: none;
}
.onoffswitch-checkbox {
display: none;
}
.onoffswitch-label {
display: block; overflow: hidden; cursor: pointer;
border: 2px solid #000000; border-radius: 20px;
}
.onoffswitch-inner {
display: block; width: 200%; margin-left: -100%;
transition: margin 0.3s ease-in 0s;
}
.onoffswitch-inner:before, .onoffswitch-inner:after {
display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px;
font-size: 16px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
box-sizing: border-box;
}
.onoffswitch-inner:before {
content: "ON";
padding-left: 5px;
background-color: #FAFAFA; color: #A87DFF;
darkMode()
}
.onoffswitch-inner:after {
content: "OFF";
padding-right: 5px;
background-color: #FAFAFA; color: #999999;
text-align: right;
}
.onoffswitch-switch {
display: block; width: 18px; margin: 6px;
background: #2E2E2E;
position: absolute; top: 0; bottom: 0;
right: 56px;
border: 2px solid #000000; border-radius: 20px;
transition: all 0.3s ease-in 0s;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
margin-left: 0;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
right: 0px;
background-color: #27A1CA;
}
body {
color: black;
}
.dark-mode {
background-color: rgb(66, 66, 66);
color: white;
}
I have been trying to understand how the button works and the switch doesn't. Does this happen because I cant use onclick inside a div tag? I am also wondering if django could cause this if there is special way to use javascript in django. I can see that the javascript file as been loaded prpperly into the site as I can get to: http://127.0.0.1:8000/static/lighting.js and see the script here.
I suggest you create an event handler for the checkbox and listen for the change event to determine whether it is checked or not to make sure that you are properly applying the dark-mode class to the body tag.
Here's a possible solution:
var body = document.body;
var checkbox = document.querySelector("#onoffswitch");
checkbox.addEventListener("change", function(event) {
var target = event.target;
var isChecked = target.checked;
if (isChecked) {
body.classList.add("dark-mode");
} else {
body.classList.remove("dark-mode");
}
});
.dark-mode {
background-color: grey;
color: white;
}
<div>
<label for="onoffswitch">
<span>Toggle dark mode on or off.</span>
</label>
<input type="checkbox" name="onoffswitch" id="onoffswitch" />
</div>
Also, the onclick event on the div element is probably not what you want, at least in your situation since you're using a checkbox to determine whether the dark-mode should be applied or not.
However, the onclick attribute on the input element that you have is missing the parenthesis (onclick="darkMode()"), so if you really want to go that route, you could still do it, but I'd recommend just dealing with the checkbox itself and checking if it's checked or not.
function toggleDarkMode() {
document.body.classList.toggle("dark-mode");
}
.dark-mode {
background-color: grey;
color: white;
}
<div>
<label for="onoffswitch">
<span>Toggle dark mode on or off.</span>
</label>
<input
type="checkbox"
name="onoffswitch"
id="onoffswitch"
onclick="toggleDarkMode()"
/>
</div>
Please check onclick function name your calling onclick="darkmode()" but in javascript you write
function myFunction() {
var element = document.body;
element.classList.toggle("dark-mode");
}
please change myFunction with darkmode
it will be look like
function darkmode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
Hopefully now it work
OBJECTIVE
Trying to change the background color of a radio input that's been styled like a button so that when the user clicks on it, the color will change according to the radio value.
EXPECTED RESULT
When click button "NEUTRAL", change button background color to white.
When click button "GOOD", change button background color to green.
When click button "WATCHLIST", change button background to yellow.
When click button "UNDER MONOTORING", change button background to red.
PROBLEM
It doesn't change the background of the button accordingly, which is what I'm trying to do.
Appreciate some help here. Thank in advance.
$(document).ready(function() {
$('label').click(function() {
if ($("input:radio[name='category']:checked").val() == 'W') {
$(this).addClass('whiteBG');
}
if ($("input:radio[name='category']:checked").val() == 'G') {
$(this).addClass('greenBG');
}
if ($("input:radio[name='category']:checked").val() == 'Y') {
$(this).addClass('yellowBG');
}
if ($("input:radio[name='category']:checked").val() == 'R') {
$(this).addClass('redBG');
}
});
});
input[type=radio],
input[type=checkbox] {
display: none;
}
label {
display: block;
appearance: button;
-webkit-appearance: button;
-moz-appearance: button;
-ms-appearance: button;
font-family: 'Roboto', sans-serif;
font-weight: 400;
background: #DDDDDD;
font-size: 1.6rem;
color: #111111;
border: 2px solid #AAAAAA;
padding: 8px;
width: 40%;
margin: 0 auto;
text-align: center;
transition: all 0.7s ease-in-out;
}
.whiteBG {
background-color: #FFF000;
}
.greenBG {
background-color: #0F0000;
}
.yellowBG {
background-color: #FF0000;
}
.redBG {
background-color: #F00000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset data-role="controlgroup">
<legend>PERSON CATEGORY SELECTION</legend>
<label for="neutral">
<input type="radio" class="button" id="neutral" name="category" value="W" >NEUTRAL</input>
</label>
<label for="good">
<input type="radio" class="button" id="good" name="category" value="G">GOOD</input>
</label>
<label for="watchlist">
<input type="radio" class="button" id="watchlist" name="category" value="Y">WATCHLIST</input>
</label>
<label for="monitor">
<input type="radio" class="button" id="monitor " name="category" value="R">UNDER MONOTORING</input>
</label>
</fieldset>
</form>
Problems in your code:
The # colour codes that you had in your CSS didn't reflect the colours you were trying to assign. These hex codes need to be either abbreviated three-digit RGB values or six-digit RGB values with two digits per colour, i.e., either #RGB or #RRGGBB, but it was like you mixed the two options by adding "000" to the end of what would otherwise be the right three-digit hex codes for the colours you wanted. Either remove the trailing 000 from each one, or change to the correct six-digit hex codes.
You didn't have any code to remove the class from a button when the other buttons are clicked.
Your JS code seems overly complicated. I would bind the click handler to the radio buttons themselves, because then this.value will give you the value of the button just clicked, thus simplifying your if conditions a lot. You can use $(this).parent() to then get to the label element to style it.
I've introduced a variable called buttons that is the jQuery object containing all of the buttons, because then inside the handler you can say buttons.not(this).parent() to get a jQuery object containing all of the other buttons' parent label elements and remove the colour class from them to make them grey again.
$(document).ready(function() {
var buttons = $("input:radio[name='category']").click(function() {
buttons.not(this).parent().removeClass('whiteBG greenBG yellowBG redBG');
var label = $(this).parent();
if (this.value == 'W') {
label.addClass('whiteBG');
} else if (this.value == 'G') {
label.addClass('greenBG');
} else if (this.value == 'Y') {
label.addClass('yellowBG');
} else if (this.value == 'R') {
label.addClass('redBG');
}
});
});
input[type=radio], input[type=checkbox] { display: none; }
label {
display: block;
appearance: button; -webkit-appearance: button; -moz-appearance: button; -ms-appearance: button;
font-family: 'Roboto', sans-serif; font-weight: 400;
background: #DDDDDD;
font-size: 1.6rem;
color: #111111;
border: 2px solid #AAAAAA;
padding: 8px;
width: 40%;
margin: 0 auto;
text-align: center;
transition: all 0.7s ease-in-out;
}
.whiteBG { background-color: #FFF; }
.greenBG { background-color: #0F0; }
.yellowBG { background-color: #FF0; }
.redBG { background-color: #F00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset data-role="controlgroup">
<legend>PERSON CATEGORY SELECTION</legend>
<label for="neutral">
<input type="radio" class="button" id="neutral" name="category" value="W" >NEUTRAL</input>
</label>
<label for="good">
<input type="radio" class="button" id="good" name="category" value="G">GOOD</input>
</label>
<label for="watchlist">
<input type="radio" class="button" id="watchlist" name="category" value="Y">WATCHLIST</input>
</label>
<label for="monitor">
<input type="radio" class="button" id="monitor" name="category" value="R">UNDER MONOTORING</input>
</label>
</fieldset>
</form>
In order to make your background-color show up, you should set appearance properties on label to none instead of button.
label {
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
-ms-appearance: none;
}
You should remove all CSS classes from your button on click before you set the new CSS class.