I have been experimenting to try to get this to work.
I have 2 checkboxes acting as part of my mobile CSS navigation menu for either side. I have a javascript that prevents more than 1 checkbox to be open at a time. It works.
Now I am trying to add an overflow:hidden to the body when either 1 of the checkboxes is checked, obviously if nothing is checked then to remove overflow:hidden, but I can't seem to get the first part to work.
I am fairly new to Javascript so any help would be appreciated. Thanks!
function selectOnlyThis(id){
var myCheckbox = document.getElementsByName("nav-check");
Array.prototype.forEach.call(myCheckbox,function(el){
if (id != el)
{
el.checked = false;
}
});
if (id.checked == false)
{
id.checked = false;
} else
{
id.checked = true;
}
if (id.checked == true)
{
$('body').css("overflow", "hidden");
}
}
// Click, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
<div class="l-btn">
<input id="lger" type="checkbox" name="nav-check" onclick="selectOnlyThis(this)"/>
<label for="lger" onclick="topFunction()"><span></span><span></span</label>
</div>
<div class="r-btn">
<input id="rger" type="checkbox" name="nav-check" onclick="selectOnlyThis(this)"/>
<label for="rger" onclick="topFunction()"><span></span><br/><div>Location</div></label>
</div>
This will do
It takes all the changes made to any checkbox and checks if the id is rger or lger and the checkbox is checked or not, then it changes the css with the jquery .css() method.
<div class="r-btn">
<input id="rger" type="checkbox" name="nav-check" />
<label for="rger" onclick="topFunction()"><span></span><br/><div>Location</div></label>
</div>
$("input:checkbox").on('change', function () {
if (($(this).attr('id')=='rger' || $(this).attr('id')=='lger') && $(this).prop('checked')) {
$('body').css("overflow", "hidden");
}
else
$('body').css("overflow", "visible");
});
Refer this fiddle.
It looks like your coming from a different programming language? :)
You will love javascript, for example a slim function for your first checkbox.
function selectOnlyThis = ({ target }) => {
const { id, checked } = target;
id === 'rger' && checked && $('body').css("overflow", "hidden");
}
Related
I'm really new to JavaScript. I'm having some issues with my JavaScript code to change the state (checked or unchecked) of my checkbox input every time I click on an anchor element (the size and content is correct in CSS).
HTML simplified
<section>
<a id="trigger"><img src="images/logo.png"></a>
<input type="checkbox" id="nav-toggle">
</section>
JavaScript
let trigger = document.getElementById('trigger');
trigger.addEventListener('click', function() {
let i = document.getElementById('nav-toggle');
if(i.checked === false) {
i.checked = true;
} else {
i.checked = false;
}
}
});
Let me know if my JavaScript code make sense, and what should I fix to make it work. Thanks!
Just tried your code and it works fine, you've just put an extra curly brace on line 9
let trigger = document.getElementById('trigger');
trigger.addEventListener('click', function() {
let i = document.getElementById('nav-toggle');
if (i.checked === false) {
i.checked = true;
} else {
i.checked = false;
}
});
<section>
<a id="trigger">toggle</a>
<input type="checkbox" id="nav-toggle">
</section>
If all you want to do is toggle the checkbox, don't use javascript, use the HTML label element and set the for attribute to the id of the checkbox.
<section>
<label for="nav-toggle"><img src="images/logo.png" alt="alternate text"></label>
<input type="checkbox" id="nav-toggle">
</section>
I have been trying to hard to add 2 Toggle Buttons having different styles (css) on Menu Bar and footer page. They are to be used for night and dark mode.
However when I use
onclick="themeToggle()" id="theme-switcher"
for both of the buttons, only one of them works.
This is my Toggle Buttons Test Page.
This is the js which is being used :
var tSwitcher = document.getElementById('theme-switcher');
let element = document.body;
let onpageLoad = localStorage.getItem("theme") || "";
if(onpageLoad != null && onpageLoad == 'dark-mode'){
tSwitcher.checked = true;
}
element.classList.add(onpageLoad);
function themeToggle(){
if(tSwitcher.checked){
localStorage.setItem('theme', 'dark-mode');
element.classList.add('dark-mode');
} else {
localStorage.setItem('theme', '');
element.classList.remove('dark-mode');
}
}
This is the code for Two Toggle buttons
<label class="switcher">
<input type="checkbox" onclick="themeToggle()" id="theme-switcher">
<div>
<i class="fas fa-sun"></i>
<i class="fas fa-arrow-left arrow"></i>
<i class="fas fa-moon"></i>
</div>
</label>
<label class="switch" style="padding: 23px 0;">
<input type="checkbox" onclick="themeToggle()" id="theme-switcher">
<div>
<span></span>
</div>
Kindly help me in solving the issue with the code as well.
Thanks for the help.
Because you are using ID in <input type="checkbox" onclick="themeToggle()" id="theme-switcher">, which you repeat in other checkbox. so only first ID in the DOM will be taken.
Change your <input type="checkbox" onclick="themeToggle()" id="theme-switcher">
To
<input type="checkbox" onclick="themeToggle()" class="theme-switcher">
And update the below code
Note: dont repeat ID
var tSwitcher = document.getElementsByClassName('theme-switcher');
let element = document.body;
let onpageLoad = localStorage.getItem("theme") || "";
if (onpageLoad != null && onpageLoad == 'dark-mode') {
for(let i = 0; i<tSwitcher.length; i++){
tSwitcher[i].checked = true;
}
}
if(onpageLoad) element.classList.add(onpageLoad);
So update your themeToggle() to
function themeToggle() {
if (event.target.checked) {
localStorage.setItem('theme', 'dark-mode');
element.classList.add('dark-mode');
} else {
localStorage.setItem('theme', '');
element.classList.remove('dark-mode');
}
}
If you are using getElementById it will return the first occurrence of that id from dom, and as you are having same id on both button it is updating the first button every time.
Instead, you can except event object, in click function, and assign event.target to get the button element.
You can't use the same ID for two or more HTML elements. Also, once you want to use this functionality in multiple elements, I strongly recommend you to not use onclick inline. Instead, you can get all switchers from your page and add a listener to them:
Get all switchers in your page
const switchers = document.querySelectorAll('.switcher');
Apply the click event listener on them
switchers.forEach((element) => {
element.addEventListener('click', (event) => {
themeToggle(event);
});
});
Finally, you must add the switcher class to all elements
<input type="checkbox" id="theme-switcher-1" class="switcher">
<input type="checkbox" id="theme-switcher-2" class="switcher">
<input type="checkbox" id="theme-switcher-3" class="switcher">
Using this approach, you can use this method all over your website or application and it's also easier to maintain.
Update: you should adjust the themeToggle() method like so:
function themeToggle(event){
var tSwitcher = event.target;
if(tSwitcher.checked){
localStorage.setItem('theme', 'dark-mode');
tSwitcher.classList.add('dark-mode'); // changed element to tSwitcher
console.log('Dark mode is on');
} else {
localStorage.setItem('theme', '');
tSwitcher.classList.remove('dark-mode'); // changed element to tSwitcher
console.log('Dark mode is off');
}
}
Example snippet
Obs.: You should adjust it into your code. I had to comment localStorage because it didn't work here.
const switchers = document.querySelectorAll('.switcher');
console.log(switchers);
switchers.forEach((element) => {
element.addEventListener('click', (event) => {
themeToggle(event);
});
});
function themeToggle(event){
var tSwitcher = event.target;
if(tSwitcher.checked){
//localStorage.setItem('theme', 'dark-mode');
tSwitcher.classList.add('dark-mode');
console.log('Dark mode is ON on ' + tSwitcher.id);
} else {
//localStorage.setItem('theme', '');
tSwitcher.classList.remove('dark-mode');
console.log('Dark mode is OFF on ' + tSwitcher.id);
}
}
<input type="checkbox" id="theme-switcher-1" class="switcher"><br />
<input type="checkbox" id="theme-switcher-2" class="switcher"><br />
<input type="checkbox" id="theme-switcher-3" class="switcher">
First of all, you cannot have two or more elements with the same id.
To detect what button is being clicked you can pass the event to the function as argument like this.
onclick="themeToggle(event)" class="switcher" id="theme-switcher-2"
Once you have the event you can get the object that has fired it (In your case the button) like this.
function themeToggle(event){
var tSwitcher = event.target;
if(tSwitcher.checked){
localStorage.setItem('theme', 'dark-mode');
element.classList.add('dark-mode');
} else {
localStorage.setItem('theme', '');
element.classList.remove('dark-mode');
}
}
EDIT
To set the default behaviour properly you have to add class="switcher" to each button and do this.
var tSwitchers = document.querySelectorAll('.switcher'));
let onpageLoad = localStorage.getItem("theme") || "";
tSwitchers.forEach((element) => {
if(onpageLoad != null && onpageLoad == 'dark-mode'){
element.checked = true;
}
});
I know it's easy to do using < button > or < input type="submit" but how would you keep this button disabled unless both input fields are filled?
<input id="one" type="text">
<input id="two" type="text">
OK
Tie an event to both inputs, and check that both have values. Then enable the link.
$('#one, #two').blur(function() {
if($('#one').val() !== "" && $('#two').val() !== "") {
$('.button').attr('href','#');
} else {
$('.button').removeAttr('href');
}
});
and change your html to:
<a class="button">OK</a>
so that the link is disabled on page load. Here's a JSFiddle demo.
$(document).ready(function() {
$inputs = $('#one,#tow');
$inputs.change(check);
$submit = $('#submit');
function check() {
var result = 1;
for (var i = 0; i < $inputs.length; i++) {
if (!$inputs[i].value) {
result = 0;
break;
}
}
if (result) {
$submit.removeAttr('disabled');
} else {
$submit.attr('disabled', 'disabled');
}
}
check();
});
suggest use angular form
$(document).ready(function(){
//$(".button").attr('disabled', "disabled");
$(".button").click(function(){
one = $("#one").val();
two = $("#two").val();
if(one && two){
///both fields filled.
return true;
}
//one or both of them is empty
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="one" type="text">
<input id="two" type="text">
OK
This is my implementation if facing this kind of situation.
First, am add disabled class onto anchor tag on page load by using this style :
.disabled {
color : gray // gray out button color
cursor : default; // make cursor to arrow
// you can do whatever styling you want
// even disabled behaviour
}
We add those class using jquery on document ready together with keyup event like so :
$(function () {
// add disabled class onto button class(anchor tag)
$(".button").addClass('disabled');
// register keyup handler on one and two element
$("#one, #two").keyup(function () {
var one = $("#one").val(),
two = $("#two").val();
// checking if both not empty, then remove class disabled
if (one && two) $(".button").removeClass('disabled');
// if not then add back disabled class
else $(".button").addClass('disabled');
});
// when we pressing those button
$('.button').click(function (e) {
// we check if those button has disabled class yet
// just return false
if ($(this).hasClass('disabled')) return false;
});
});
DEMO
I have this code in html I want to change the checkbox check and uncheck event using javascript on some event so I am calling function ChangeCheckBox() on button click
<div>
<label class="checkbox line">
<input type="checkbox" id="Add" />Add</label>
</div>
<script>
function ChangeCheckBox() {
var AddCheck = 0;
if (AddCheck == 1) {
document.getElementById("Add").checked = true;
} else {
document.getElementById("Add").checked = false;
}
}
</script>
So in above condition check box should unchecked but its not happening checkbox is remaining checked after running this code
Since you are setting AddCheck = 0;, of course it will not keep it's state, because you are reseting the value. If you want to simulate a toggle, here's a simpler alternative.
<script>
function ChangeCheckBox() {
var el = document.getElementById("Add");
el.checked = !el.checked;
}
</script>
How do you link 'ChangeCheckBox()' to your button ? Can you post this code too ?
The problem is probably because the button refresh your page and so, the checkbox return to it initial state.
i have a question about JavaScript addEventListener,
i have two div and in this divs there is a input text.
(please with JavaScript)
i want to register a click only for div not for the input.
<div id="deneme">
<input style="margin: 10px;" type="textbox" />
<div id="new"></div>
</div>
JavaScript:
var divTag = document.getElementsByTagName("div");
for (var i = 0; i < divTag.length; i++) {
if (divTag[i].tagName == "DIV" || divTag[i].tagName == "div") {
if (divTag[i].addEventListener) {
divTag[i].addEventListener('click', redirect,false);
}
else if (divTag[i].attachEvent) {
divTag[i].attachEvent('on' + 'click',redirect);
}
}
}
function redirect(e) {
alert("redirect");
e.stopPropagation();
}
CSS :
#deneme {
width:200px;
height:200px;
background-color:yellow;
}
#new{
width:20px;
height:20px;
background-color:green;
}
can you help me?
Thanks in advance.
If you only have two divs, use document.getElementById instead of getElementsByTagName. You can add the two elements to an array and still iterate over them with your loop.
Otherwise, you can modify your event handler to check that e.target isn't the input.
As a side note, if you're going to be doing a lot of event handling, consider using jQuery. It'll make your life easier in that you do not need to worry about cross-browser compatibility.
You will need to move the input outside the outer div and use CSS to reposition the input above that div. See this Fiddle.
<input style="margin: 10px;" type="textbox" />
<div id="deneme">
<div id="new"></div>
</div>
input {
position: absolute;
}
Edit: Okay, if you cannot move the input as suggested above, you need to test which element triggered the event. I updated the fiddle accordingly.
function is(type, obj) {
// source: http://bonsaiden.github.io/JavaScript-Garden/#the-class-of-an-object
var class = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && class === type;
}
function redirect(e) {
if ( is('HTMLInputElement', e.target) ) {
return false;
}
alert("redirect");
e.stopPropagation();
}
Not that I like such kind of solution, but if you only want to redirect from the div you can check what kind of element has been pressed, by getting the target and its constructor name.
Code (HTML):
<div id="deneme">
<input style="margin: 10px;" type="textbox" />
<div id="new"></div>
</div>
Code (JS):
var divTag = document.getElementsByTagName("div");
for (var i = 0; i < divTag.length; i++) {
if (divTag[i].tagName == "DIV" || divTag[i].tagName == "div") {
if (divTag[i].addEventListener) {
divTag[i].addEventListener('click', redirect,false);
}
else if (divTag[i].attachEvent) {
divTag[i].attachEvent('on' + 'click',redirect);
}
}
}
function redirect(e) {
if (e.target.constructor.name == "HTMLDivElement") {
alert("redirect");
}
e.stopPropagation();
}
Working fiddle:
http://jsfiddle.net/d5z8zgf0/
You may want to check out JQuery for your solution. Try something like:
$("#deneme").click(function(){
alert("The div was clicked." /* Or do something else */);
});
Also there may be a similar question here: addEventListener vs onclick