Toggle display with javascript vanilla - javascript

How to toggle display with Javascript Vanilla when I click a checkbox.
I tried with only one element and it works but when there is more than one...I put this in my code-->
function OnlyOK(){
var ul = document.getElementsByClassName('RQ');
for (i = 0; i < ul.length; i++) {
ul[i].style.display = 'none';
}
//else ul[i].style.display = 'block';???
}
And the case of toggle display(none,block) only one element (1 first element)...This Works!!
function OnlyOK(){
var ul = document.getElementsByClassName('RQ');
ul.style.display = ul.style.display === 'none' ? '' : 'none';
}
I tried getElementsById too! but I prefer to work with class.

So basically you want to hide some elements when you click and check a checkbox and show them again after you uncheck the checkbox, right?
You can achieve such a thing like this:
function OnlyOK(flag){
var ul = document.getElementsByClassName('RQ');
for (i = 0; i < ul.length; i++) {
if (flag) {
ul[i].style.display = 'none';
} else {
ul[i].style.display = 'block';
}
}
}
document.querySelector('#ck')
.addEventListener('change', function(event) {
console.log(event);
OnlyOK(event.target.checked);
});
With this HTML:
<ul>
<li class="RQ">Some item to hide</li>
<li class="RQ">Hide me</li>
<li class="RQ">I will be gone</li>
<li>I do not have class :(</li>
</ul>
<input type="checkbox" id="ck"/>
Here is a working example.

<input type="checkbox" class="eq" onchange="onlyOk(this)"></input>
function onlyOk(obj){
var rq = document.getElementsByClassName("RQ");
var i;
var display = obj.checked ? "none" : "";
for (i = 0; i > rq.length; i++){
rq[i].style.display = display;
}
}

Related

Javascript passing info from one function to another

I've created a JS function that hides a certain amount of breadcrumbs if there are too many. They are replaced by a button (ellipsis), when you click the button the hidden breadcrumbs are revealed.
The Problem: I loop through the breadcrumbs to see if there are enough to hide. If there are I hide them. But I can't figure out how to then call the code to create the button. If I call the button code in the loop I get more than 1 button generated.
Right now the button will always appear whether there are enough breadcrumbs to hide or not.
In my mind, I would have the for loop with the if statement return true to what would then be the button function. But I can't figure out how to do this. Please offer any pointers for restructuring this code if you can.
Here's a Codepen: https://codepen.io/sibarad/pen/GRvpEbp
Basic HTML:
<nav aria-label="breadcrumb">
<ol class="c-breadcrumb mb-7 md:mb-8">
<li class="c-breadcrumb-item">
Breadcrumb 1
</li>
<li class="c-breadcrumb-item">
Breadcrumb 2
</li>
<li class="c-breadcrumb-item">
Longer Breadcrumb Name 03
</li>
</ol>
</nav>
Javascript:
function breadcrumb() {
// Target specific breadcrumbs, not 1st or last 2
let hiddenbreadcrumb = document.querySelectorAll('.c-breadcrumb-item:nth-child(1n+2):nth-last-child(n+3)');
// Loop through select breadcrumbs, if length is greater than x hide them.
for (var i = 0; i < hiddenbreadcrumb.length; i++) {
if(hiddenbreadcrumb.length >= 3) {
hiddenbreadcrumb[i].style.display = "none";
}
}
// This would be the button function, but I don't know how to engage this only if the if statement above was met.
let li = document.createElement('li');
li.className = 'c-breadcrumb-item';
let ellipbutton = document.createElement('button');
ellipbutton.type = 'button';
ellipbutton.innerHTML = '...';
ellipbutton.className = 'c-breadcrumb_btn u-btn-clear';
ellipbutton.onclick = function() {
console.log("clicked");
for (var i = 0; i < hiddenbreadcrumb.length; i++) {
hiddenbreadcrumb[i].style.display = "flex";
}
li.style.display = "none";
};
li.appendChild(ellipbutton);
let container = document.querySelector('.c-breadcrumb-item:first-child');
container.insertAdjacentElement("afterend", li);
}
breadcrumb();
We can refactor your code slightly to achieve this - the if statement which checks whether there are more than 3 breadcrumbs doesn't need to be inside the for loop - it's redundant to keep checking the same value multiple times.
If we move that outside the loop then it can
a) prevent unnecessary looping when there aren't enough breadcrumbs, and
b) wrap around the button creation code as well, which should solve your problem.
For example:
if (hiddenbreadcrumb.length >= 3) {
for (var i = 0; i < hiddenbreadcrumb.length; i++) {
hiddenbreadcrumb[i].style.display = "none";
}
let li = document.createElement('li');
li.className = 'c-breadcrumb-item';
let ellipbutton = document.createElement('button');
ellipbutton.type = 'button';
ellipbutton.innerHTML = '...';
ellipbutton.className = 'c-breadcrumb_btn u-btn-clear';
ellipbutton.onclick = function() {
console.log("clicked");
for (var i = 0; i < hiddenbreadcrumb.length; i++) {
hiddenbreadcrumb[i].style.display = "flex";
}
li.style.display = "none";
};
let container = document.querySelector('.c-breadcrumb-item:first-child');
container.insertAdjacentElement("afterend", li);
}
It looks like some small initialization issues. This should correct it:
Change this:
let hiddenbreadcrumb = document.querySelectorAll('.c-breadcrumb-item:nth-child(1n+2):nth-last-child(n+3)');
// Loop through select breadcrumbs, if length is greater than x hide them.
for (var i = 0; i < hiddenbreadcrumb.length; i++) {
if(hiddenbreadcrumb.length >= 3) {
hiddenbreadcrumb[i].style.display = "none";
}
}
to this:
let hiddenbreadcrumb = document.querySelectorAll('.c-breadcrumb-item');
if(hiddenbreadcrumb.length < 3)
return
for (var i = 1; i < hiddenbreadcrumb.length - 1; i++) {
hiddenbreadcrumb[i].style.display = "none";
}
Try this... it allows 3 li items as item1 ... item2ndLast, itemLast
(function () {
"use strict";
function breadcrumb() {
let hiddenbreadcrumb = document.querySelectorAll(".c-breadcrumb-item:nth-child(1n+2)");
if (hiddenbreadcrumb.length <= 3) return;
for (var i = 1; i < hiddenbreadcrumb.length - 1; i++) {
hiddenbreadcrumb[i].style.display = "none";
}
let li = document.createElement("li");
li.className = "c-breadcrumb-item";
let ellipbutton = document.createElement("button");
ellipbutton.type = "button";
ellipbutton.innerHTML = "...";
ellipbutton.className = "c-breadcrumb_btn u-btn-clear";
ellipbutton.onclick = function () {
console.log("clicked");
for (var i = 0; i < hiddenbreadcrumb.length; i++) {
hiddenbreadcrumb[i].style.display = "flex";
}
li.style.display = "none";
};
li.appendChild(ellipbutton);
let container = document.querySelector(".c-breadcrumb-item:first-child");
container.insertAdjacentElement("afterend", li);
}
breadcrumb();
})();

Make all other Divs dissapear javascript

I got a Script Which makes me onclick showing all Divs with Specific id
This is the Selector
<a onclick="filterGal('simpleCart_shelfItem item Sonnenbrillen')" href="javascript:void(0);">Sonnenbrillen</a>
this is my Script
function filterGal(foo) {
var toHide = document.getElementsByClassName(foo);
for (i = 0; i < toHide.length; i++) {
toHide[i].style.display = 'block';
}
}
So now my question how can i only show specific div with classname and display none the other div with other classnames?
Try this :
function filterGal(foo) {
var toHide = document.getElementsByTagName('div');
for (i = 0; i < toHide.length; i++) {
toHide[i].style.display = 'none';
}
var toShow = document.getElementsByClassName(foo);
for (i = 0; i < toShow.length; i++) {
toShow[i].style.display = 'block';
}
}
Can be improved by skiping in the first loop div which match your classes.
I just show you add jquery tag so you just need to do this :
function filterGal(foo) {
$( "div:not("+foo+")" ).hide();
}
Exemple : http://jsfiddle.net/ACjeZ/1
This is what I would try:
$("div").Hide();
$("." + foo).Show();

Add class active when clicking menu link with JAVASCRIPT

HTML
<div id="top" class="shadow">
<ul class="gprc">
<li>Home</li>
<li>Text1</li>
<li>Text2</li>
<li>Text3</li>
<li>Text4</li>
</ul>
Javascript
window.onload = setActive;
function setActive() {
aObj = document.getElementById('top').getElementsByTagName('a');
var found = false;
for (i = 0; i < aObj.length; i++) {
if (document.location.href.indexOf(aObj[i].href) >= 0) {
aObj[i].className = 'active';
found = true;
}
}
if (!found) {
aObj[0].className = 'active';
}
}
The problem is that the menu home link remains selected or active all the time even if i click on other links and I would like to make it not selected on loading of the page and also to remain non-selected while other link that i clicked and i am on the specific landing page remains selected. Please only Javascript no JQUERY.
Try this:
window.onload = setActive;
function setActive() {
var aObj = document.getElementById('top').getElementsByTagName('a');
var found = false;
for(var i=aObj.length-1; i>=1 && !found; i--) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
found = true;
}
}
//if you never want home selected remove the next
if(!found && document.location.href.replace(/\/$/, "") == aObj[0].href.replace(/\/$/, ""))
aObj[0].className = 'active';
}
With this way you start at the end of the list, and when you find a coincidence it stop the search of an active link.
I hope it helps you
function setActive() {
var top = document.getElementById('top'),
aObj = top.getElementsByTagName('a'),
href = document.location.href,
found = false;
for (var i = 0; i < aObj.length || !found; i++) {
if (href.indexOf(aObj[i].href) >= 0) {
aObj[i].className = 'active';
found = true;
}
}
if (!found) {
aObj[0].className = 'active';
}
//Listen for link clicks
function listener(e) {
if(e.target.tagName === "A") {
for (var i = 0; i<aObj.length; i++) {//remove previous class
aObj[i].className = "";
}
e.target.className = "active";
}
}
if(top.addEventListener) {
top.addEventListener(listener);
} else if(top.attachEvent) {
top.attachEvent(listener);
}
}
You're going to need to listen to the click event so you can determine if one of your links is pressed. I'm going to do this using some simple delegation

Changing classes in a menu with Javascript

I am looking to create a very simple functionality of clicking on a menu tab and it changes color to let you know what page you are on. I am a novice so please take it easy on me...lol
/Menu in php header file/
<ul class="tabs" id="tabs">
<li class="selected">Home</li>
<li class="inactive">Bio</li>
<li class="inactive">Photo</li>
<li class="inactive">Thank</li>
<li class="inactive">Contact</li>
</ul>
/*This is the JavaScript file*/
window.onload = initPage;
function initPage() {
var tabs = document.getElementById("tabs").getElementsByTagName("li");
for (var i=0; i<tabs.length; i++){
var links = tabs[i];
links.onclick = tabClicked;
}
}
function tabClicked(){
var tabId = this.id;
document.getElementById(tabId).classList.toggle("selected");
var tabs = document.getElementById("tabs").getElementsByTagName("li");
for (var i=0; i < tabs.length; i++){
var currentTab = tabs[i];
if (currentTab.id !== tabId){
currentTab.class = "selected";
} else {
currentTab.class = "inactive";
}
}
}
element.setAttribute("class", "className");
You are using ids in your code but you don't have provided it in your markup. so give ids to li elements and try this.
function tabClicked(){
var tabId = this.id;
document.getElementById(tabId).classList.toggle("selected");
var tabs = document.getElementById("tabs").getElementsByTagName("li");
for (var i=0; i < tabs.length; i++){
var currentTab = tabs[i];
if (currentTab.id !== tabId){
currentTab.className = "inactive";
} else {
currentTab.className= "selected";
}
}
}
JS Fiddle Demo
Store a reference to each of the list items.
Create a variable to keep track of the current tab.
In an onclick function for each element (or you could use one onclick and just use some conditions), change the class attribute of the element by using the setAttribute() method.
Like this:
function onFirstTabClick() {
clearSelected();
tabVariable1.setAttribute("class","some-new-class");
}
function() clearSelected() {
switch(currentSelectedTrackerVariable) {
case 1: tabVariable1.setAttribute("class","some-new-class");
break;
// Do this for the amount of tabs that you have.
}
}
Working FIDDLE Demo
There is no need to define functions globally. Write all them in one package. The code below, works correctly with your HTML markup.
<script>
window.onload = function () {
var tab = document.getElementById('tabs');
var lis = tab.getElementsByTagName('li');
for (var i = 0, l = lis.length; i < l; i++) {
lis[i].onclick = function () {
for (var j = 0; j < l; j++) {
lis[j]["className"] = "inactive";
}
this["className"] = "selected";
};
}
};
</script>
If you use jQuery, then tabClicked can run:
jQuery('.selected').removeClass('selected').addClass('inactive');
jQuery(this).removeClass('inactive').addClass('selected');

Is there a way to show these hidden element with mouseover?

In my html code I have a list of these <li> elements:
<li class="liitem" id="183"><span> Google </span><br>
<ul><li><span>gmail.com </span><span id="183" style="float:right;display:none;">delete</span></li></ul></li>
I want this:
When there is a mouseover on a <li> element of the "liitem" class, then set display:block of the span with the same id ( 183 in this case ).
I have writed this code but it's incomplete and I don't know how to do:
var elms = document.getElementsByTagName('li');
for (var i = 0; i < elms.length; i++){
if (elms[i].getAttribute('class') === 'liitem'){
elms[i].onmouseover = function(){
//set display:block
}
elms[i].onmouseout = function(){
//set display:none
}
}
}
you have set an id with the same value id should be unique. so you could add a value to the id to make it diferent for the liitem's id. like.
Just make sure there is no space to be safe between the a and span.
<ul>
<li class="liitem" id="183"><span> Google </span><br>
<ul><li><span>gmail.com</span><span style="float:right;display:none;">delete</span></li></ul>
<ul><li><span>docs</span><span style="float:right;display:none;">delete</span></li></ul>
</li>
</ul>
.
var elms = document.getElementsByTagName('li'),
emls_len = elms.length;
for (var i = 0; i < emls_len; i++){
if (elms[i].className == 'liitem'){
var arr_sub_uls = document.getElementById(elms[i].id).getElementsByTagName('ul');
// for each UL within the liitem
for (var j = 0; j < arr_sub_uls.length; j++){
// assign id's to the span around delete
var actionis = arr_sub_uls[j].childNodes[0].childNodes[1].id = elms[i].id + "_" + j; // elms[i].id is the liitem id and j is the number of uls'
// attach the event handler
addEventHandler(arr_sub_uls[j].childNodes[0],actionis)
}
}
}
function addEventHandler(s, actionis){
s.onmouseover = function(){ document.getElementById(actionis).style.display = "block" }
s.onmouseout = function(){ document.getElementById(actionis).style.display = "none" }
}
see fiddle: http://jsfiddle.net/EW2cm/1/
You can do this:
elms[i].style.display = "block";
and
elms[i].style.display = "none";

Categories

Resources